简体   繁体   中英

Pythonic way to “merge” two lists to a list of tuples

Suppose I have two lists

L1 = [1,2,3]

and

L2 = [a,b,c]

Whats the fastest way to convert this to the list M = [(1,a),(2,b),(3,c)] ?

I tried M = [(x,y) for x in L1 for y in L2] but this gives me all possible combination of elements. Sure I can write a loop to do it, but is there a more pythonic way to do this?

Use zip() .

This function returns a list of tuples, where the i -th tuple contains the i -th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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