在Python中使用多个参数进行映射,包括一个具有默认值的参数

时间:2018-08-18 05:02:18

标签: python python-3.x default

我正在使用Python3.6,并试图找出可以将map与多个参数一起使用的方式。

我跑步时

def multiply(x, y, z):
    return x * y * z

products = map(multiply, [3,6], [1,8], [3,5])

list(products)按预期返回[9, 240]

但是,当我为z指定默认值时,

def multiply(x, y, z = [3,5]):
    return x * y * z

products = map(multiply, [3,6], [1,8])

list(product)返回

[[3, 5, 3, 5, 3, 5],
 [3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5,
  3,
  5]]

在两种情况下,Python为什么运行map的方式不同?

3 个答案:

答案 0 :(得分:1)

尝试:

l=iter([3,5])
def multiply(x, y, z = l):
    return x * y * next(z)

products = map(multiply, [3,6], [1,8])

那么list(products)将是:[9, 240]

说明:

您的代码不起作用,因为您要将一个数字与一个列表相乘(因此,基本上它将是一个重复n次的列表),因此您需要始终获取下一个值,因此对next进行操作列表中的iter

请参阅:Python: next() function

答案 1 :(得分:1)

在使用map执行期间设置z的默认值时,会发生这种情况:

3 * 1 * [3,5]
6 * 8 * [3,5]

因此,为了使map能够按预期工作,您应该明确给出列表作为其中的一个参数,在这种情况下,z的默认值不是map的直接参数。希望这是有道理的。

答案 2 :(得分:1)

我认为应该使用reduce而不是mapThis link explain difference between reduce and map。使用reduce应该

import functools
expected=functools.reduce(lambda acc,current:[acc[0]*current[0],acc[1]*current[1]],([3,6], [1,8], [3,5]))
print(expected) # [9, 240]

根据此docreduce大致等同于:

def reduce(function, iterable, initializer=None):
    it = iter(iterable)
    if initializer is None:
        value = next(it)
    else:
        value = initializer
    for element in it:
        value = function(value, element)
    return value