0

I want to pass a list of None in a map function but it doesn't work.

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)

I have this message error:

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

4 回答 4

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]

过滤结果为 3 个参数func1

>>> 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]
于 2013-04-22T16:23:31.257 回答
0

第二个参数 d 应该是 SEQUENCE ,将其作为列表或元组..

于 2013-04-22T16:52:16.923 回答
0

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

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)
于 2013-04-22T16:22:59.950 回答
0

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

map((lambda *x): func1(*x)), (a,b,c,d))
于 2013-04-22T16:22:26.010 回答