【问题标题】:map in Python with multiple arguments, including one with a default value在 Python 中使用多个参数映射,包括一个具有默认值的参数
【发布时间】:2019-01-25 02:08:11
【问题描述】:

我正在使用 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 的方式不同?

【问题讨论】:

  • 因为z是一个列表..
  • 当然,但是z 不是在这两种情况下的列表吗?
  • 好的,我来编辑
  • @Isaac 不,它不是两种情况下的列表。当您使用map 时,它会传递列表中的元素

标签: python python-3.x default


【解决方案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 到 @987654326列表的@

见:Python: next() function

【讨论】:

  • 这行得通。虽然你知道为什么代码在 z 没有默认值时乘以 z' to x*y`,而在 z 有默认值时重复 z x*y 次?
  • @Isaac 我不完全理解你的意思,但正如你在函数中知道的那样,你正在对 list 而不是 int 所以基本上是x*y*[3,5]
【解决方案2】:

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

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

因此,您的输出,为了让 map 按您的意愿工作,您应该明确地将列表作为它的参数之一,在您的情况下,z 的默认值不是 map 的直接参数。希望这是有道理的。

【讨论】:

    【解决方案3】:

    我认为应该使用reduce而不是map.This 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]
    

    据此doc.reduce大致相当于:

    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
    

    【讨论】:

    • 我同意,但如果我要使用 reduce,我认为这可能会更干净:expected = functools. reduce(lambda x, y : [z[0]*z[1] for z in zip(x,y)] , ([3,6], [1,8], [3,5])) 谢谢你的想法。
    猜你喜欢
    • 1970-01-01
    • 2014-10-12
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-09
    相关资源
    最近更新 更多