简体   繁体   English

加入两个列表以创建一个新列表

[英]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 Itertools具有类似的功能与zip_longest ,这是一个比快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]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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