Python How to pair two list by lambda and map

2019-02-28 22:57发布

For example, I have following two lists

listA=['one', 'two' , 'three'] listB=['apple','cherry','watermelon']

How can I pair those two lists to get this output, using map and lambda?

one apple
two cherry
three watermelon

I know how to do it by the list comprehension,

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

but I can't figure out a map and lambda solution. Any ideas?

标签: python lambda
5条回答
Fickle 薄情
2楼-- · 2019-02-28 23:06

Using list comprehension and zip:

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

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

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

Output:

['one apple', 'two cherry', 'three watermelon']
查看更多
smile是对你的礼貌
3楼-- · 2019-02-28 23:21

You can use zip like below:

for item in zip(list_1, list_2):
    print(item)
查看更多
smile是对你的礼貌
4楼-- · 2019-02-28 23:21

specifically using map and lambda as asked...

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

though I'd probably break that up to make it more readable

zipped   = zip(listA,listB)
tup2str  = lambda tup: ' '.join(list(tup))
result   = list(map(tup2str, zipped))
# ['one apple', 'two cherry', 'three watermelon']

EDITED - per comment below, listCombined = list(zip(listA,listB)) was a waste

查看更多
聊天终结者
5楼-- · 2019-02-28 23:23

The easiest solution would be to simply use zip as in:

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

I guess it would be possible to use map and lambdas, but that would just needlessly complicate things as this is really the ideal case for zip.

查看更多
Explosion°爆炸
6楼-- · 2019-02-28 23:23

Here what I got based on what you need (map and lambda),

Input:

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

Output:

['one apple', 'two cherry', 'three watermelon']
查看更多
登录 后发表回答