Python的拉链行为与*

问题描述 投票:1回答:2

为什么存在与拉链功能(实施例号3)以下结果:

l = list(zip(['1', '2'], ['a', 'b']))
print(l)
# [('1', 'a'), ('2', 'b')] - ok, zip works as expected

l = list(map(lambda t: t[0] + t[1], zip(['1', '2'], ['a', 'b'])))
print(l)
# ['1a', '2b'] - nice, I have expected result with argument passed as tuple

l = list(map(lambda x, y: x + y, *zip(['1', '2'], ['a', 'b'])))
print(l)
#['12', 'ab'] - Why?! I just added * and it broke everything?

此外,如果I型:

l = list(map(lambda x, y: x + y, *zip(['1', '2', '3'], ['a', 'b', 'c'])))
print(l)

我得到以下错误:

Traceback (most recent call last):
  File "test.py", line 9, in <module>
    l = list(map(lambda x, y: x + y, *zip(['1', '2', '3'], ['a', 'b', 'c'])))
TypeError: <lambda>() takes 2 positional arguments but 3 were given
python
2个回答
3
投票

在开始使用此迭代器:

map(lambda x, y: x + y, *zip(['1', '2'], ['a', 'b']))

当您使用zip为“转”的名单:

zip(['1', '2'], ['a', 'b']) -> [('1', 'a'), ('2', 'b')]

这意味着map有效地接收这样的:

map(lambda x, y: x + y, *[('1', 'a'), ('2', 'b')])

这是equivalent到:

map(lambda x, y: x + y, ('1', 'a'), ('2', 'b'))

具有多于一个甲map迭代需要一个元件断开它们各自,并将它们传递到功能,所以其结果是:

[(lambda x, y: x + y)('1', '2'), (lambda x, y: x + y)('a', 'b')] == ['12', 'ab']

我不知道你的困惑来自于,但这应该帮助。请检查连接的更多详细信息,文档。


1
投票
l = list(map(lambda x, y: x + y, *zip(['1', '2'], ['a', 'b'])))
print(l)

输出:

['12', 'ab']

这里*zip(['1', '2'], ['a', 'b'])返回两个元('1', 'a') ('2', 'b')(注意有两个元组之间没有逗号,这意味着它们都得到了解压由于*操作)

拉姆达函数连接的每个元组的,当你在两者同时迭代通过多个迭代项目的map功能,它只是迭代作为第一要素!在每次迭代它需要从每个元组并连接一个元素。

与第一个类似,表达式返回*zip(['1', '2', '3'], ['a', 'b', 'c'])三元组('1', 'a') ('2', 'b') ('3', 'c')因此,在每个循环map刚刚超过所有的三元组迭代,从而获取三个参数。

© www.soinside.com 2019 - 2024. All rights reserved.