简体   繁体   中英

Joining two lists to create a new list

I have two lists and a constant number

x =[47, 78, 35, 70, 28, 41]
y = [45, 79, 30, 83, 71, 46]
z=10

I want to create a new list which looks like

a=[[47,45,10],
   [78,79,10],
   [35,30,10],
   [70,83,10],
   [28,71,10],
   [41,46,10]]

Try this

res = [[a, b, z] for a, b in zip(x, y)]
print(res)

Output:

[[47, 45, 10],
 [78, 79, 10],
 [35, 30, 10],
 [70, 83, 10],
 [28, 71, 10],
 [41, 46, 10]]

Itertools has similar functionality with zip_longest and it's a quicker than zip

from itertools import zip_longest

[[a, b, z] for a,b in zip_longest(x,y)]

>>> 
[[47, 45, 10],
 [78, 79, 10],
 [35, 30, 10],
 [70, 83, 10],
 [28, 71, 10],
 [41, 46, 10]]

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