【问题标题】:Python : Map function with none type list as parameterPython:使用无类型列表作为参数的映射函数
【发布时间】:2013-04-22 16:19:09
【问题描述】:

我想在 map 函数中传递一个 None 列表,但它不起作用。

a = ['azerty','uiop']
b = ['qsdfg','hjklm']
c = ['wxc','vbn']
d = None

def func1(*y):
    print 'y:',y

map((lambda *x: func1(*x)), a,b,c,d)

我收到此消息错误:

TypeError: argument 5 to map() must support iteration.

【问题讨论】:

  • 请注意,鉴于您正在制作的功能,看起来您想要itertools.starmap() 而不是map()(它什么都不做,但可能意味着lambda x: func1(*x))。请注意,无论您在这里做什么,d 都会导致问题。
  • 实际上,鉴于d = None,我认为OP更有可能想要map(..., (a,b,c,d))的行为,并假设None会在没有参数的情况下调用该函数。
  • @Lattyware:不完全; map() 有多个列表 zips 列表。 starmap() 一个一个地应用列表。
  • @MartijnPieters 我从奇怪的lambda 中汲取了starmap() 的用法——如果提问者确实想要zip() 类似的行为,那么结合starmap()zip() 就可以了很好。
  • @Lattyware:让它与starmapzip 一起工作变得非常冗长; map() 语法在这里更紧凑。

标签: python list nonetype map-function


【解决方案1】:

用空列表替换None

map(func1, a or [], b or [], c or [], d or [])

或过滤列表:

map(func1, *filter(None, (a, b, c, d)))

filter() 调用将 d 从列表中完全删除,而第一个选项为您的函数调用提供 None 值。

我删除了 lambda,这里是多余的。

使用or [] 选项,第四个参数是None

>>> map(func1, a or [], b or [], c or [], d or [])
y: ('azerty', 'qsdfg', 'wxc', None)
y: ('uiop', 'hjklm', 'vbn', None)
[None, None]

过滤结果为func1 的 3 个参数:

>>> map(func1, *filter(None, (a, b, c, d)))
y: ('azerty', 'qsdfg', 'wxc')
y: ('uiop', 'hjklm', 'vbn')
[None, None]

您也可以使用itertools.starmap(),但这有点冗长:

>>> list(starmap(func1, zip(*filter(None, (a, b, c, d)))))
y: ('azerty', 'qsdfg', 'wxc')
y: ('uiop', 'hjklm', 'vbn')
[None, None]

【讨论】:

  • 值得注意的是,lambda *x: func1(*x) 完全等同于func1(除了一个毫无意义的额外功能)。
  • 感谢您的帮助,这正是我想要的!
  • 我还有一个问题,如果我有一个 var u='string' 并且我的函数 func1 是这样的:def func1(z,y*) 我如何在我的地图函数中传递我的参数 u?
  • @Tof:使用functools.partial()map(partial(func1, u), ...)
  • @MartijnPieters 太完美了!!但只是想知道,还有另一种解决方案吗?
【解决方案2】:

制作第二个参数来映射列表或元组:

map((lambda *x): func1(*x)), (a,b,c,d))

【讨论】:

    【解决方案3】:

    错误消息几乎说明了一切:None 不可迭代。 map 的参数应该是可迭代的:

    map(func, *iterables) --> map object
    
    Make an iterator that computes the function using arguments from
    each of the iterables.  Stops when the shortest iterable is exhausted.
    

    根据您想要实现的目标,您可以:

    • None更改为空列表;
    • map 你的函数在[a, b, c, d] 列表中

    还请注意,您可以直接映射func1,无需 lambda:

    map(func1, *iterables)
    

    【讨论】:

      【解决方案4】:

      第二个参数 d 应该是一个 SEQUENCE ,使它成为一个列表或元组..

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-21
        • 2019-03-20
        • 1970-01-01
        • 2023-01-05
        • 2011-06-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多