简体   繁体   English

Python:不带类型列表作为参数的Map函数

[英]Python : Map function with none type list as parameter

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.

Replace None with an empty list: 用空列表替换None

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

or filter the lists: 或过滤列表:

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

The filter() call removes d from the list altogether, while the first option gives you None values to your function call. filter()调用将从列表中完全删除d ,而第一个选项为您的函数调用提供None值。

I removed the lambda, it is redundant here. 我删除了lambda,在这里是多余的。

With the or [] option, the 4th argument is None : 使用or []选项,第四个参数是None

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

Filtering results in 3 arguments to func1 : 过滤结果为func1 3个参数:

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

You could use itertools.starmap() as well, but that gets a little verbose: 您也可以使用itertools.starmap() ,但这有点冗长:

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

输入第二个参数以映射列表或元组:

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

The error message pretty much says it all: None is not iterable. 错误消息几乎说明了一切: None是不可迭代的。 Arguments to map should be iterable: 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.

Depending on what you want to achieve, you can: 根据您想要实现的目标,您可以:

  • change None to an empty list; None更改为空列表;
  • map your function on a list of [a, b, c, d] 将函数map[a, b, c, d]

Also note that you can map func1 directly, without a lambda: 另请注意,您可以直接映射func1 ,而无需使用lambda:

map(func1, *iterables)

第二个参数d应该是SEQUENCE,使其成为列表或元组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM