Python如何使用lambda和map函数将两个列表配对

22
例如,我有以下两个列表 listA = ['one', 'two', 'three'] listB = ['apple', 'cherry', 'watermelon']
如何使用map和lambda将这两个列表配对以获得以下输出?
one apple
two cherry
three watermelon

我知道如何使用列表推导式来完成它。

[print(listA[i], listB[i]) for i in range(len(listA))]

但我无法想出一种maplambda的解决方案。有什么想法吗?

Translated:

但我无法想出一种maplambda的解决方案。有什么想法吗?


4
为什么不用 zip() 函数? - Ajax1234
2
这是 zip() 的标准用法。 - Akshat Mahajan
print(..)?为什么是 print?此外这看起来像作业。 - Willem Van Onsem
你不能在你的情况下使用列表推导。 - ettanany
在列表推导式中不要使用print。这是非常糟糕的风格,因为它在函数构造内部使用了副作用。 - juanpa.arrivillaga
6个回答

35

根据您的需求(地图和lambda),我得到了以下内容:

输入:

listA=['one', 'two' , 'three']
listB=['apple','cherry','watermelon']
list(map(lambda x, y: x+ ' ' +y, listA, listB))

输出:

['one apple', 'two cherry', 'three watermelon']

16

最简单的解决方案是直接使用zip函数,例如:

>>> listA=['one', 'two' , 'three']
>>> listB=['apple','cherry','watermelon']
>>> list(zip(listA, listB))
[('one', 'apple'), ('two', 'cherry'), ('three', 'watermelon')]

我想可以使用 map 和 lambda,但这只会不必要地使事情变得复杂,因为这真的是使用 zip 的理想情况。


4

使用列表推导和zip函数:

listA=['one', 'two' , 'three']

listB=['apple','cherry','watermelon']

new_list = [a+" "+b for a, b in zip(listA, listB)]

输出:

['one apple', 'two cherry', 'three watermelon']

4

假设有两个列表list1和list2,我们可以将它们成对组合成列表或元组类型。

list1=['1', '2' , '3']
list2=['3','2','1']
output = list (map (  lambda x,y: [x,y], list1,list2    ))
print(output)

输出:

[['1', '3'], ['2', '2'], ['3', '1']]

3
您可以按如下方式使用 zip

for item in zip(list_1, list_2):
    print(item)

3

特别是按照要求使用map和lambda...

list(map(lambda tup: ' '.join(list(tup)), zip(listA,listB)))

虽然我可能会将其分开以使其更易读,但保留原有的HTML标签。
zipped   = zip(listA,listB)
tup2str  = lambda tup: ' '.join(list(tup))
result   = list(map(tup2str, zipped))
# ['one apple', 'two cherry', 'three watermelon']

根据下面的评论,listCombined = list(zip(listA,listB))是浪费的。


2
不要使用 list(zip(listA,listB)))... 你为什么要将你的 zip 迭代器转换成列表?这样做完全违背了它的初衷。 - juanpa.arrivillaga

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接