[英]Python zip the first element of a list with the rest of elements
I have a list 我有一份清单
mylist = [(0,0,0),(1,1,1),(2,2,2),(3,3,3)]
i wish to find a code saving method to zip the first element mylist[0]
with the rest of the list element mylist[1:]
in order to get a new list as: 我希望找到一个代码保存方法来将第一个元素
mylist[0]
与列表元素mylist[1:]
的其余部分压缩,以获得一个新列表:
[((0,0,0),(1,1,1)),((0,0,0),(2,2,2)),((0,0,0),(3,3,3))]
Using zip
: 使用
zip
:
>>> mylist = [(0,0,0),(1,1,1),(2,2,2),(3,3,3)]
>>> zip([mylist[0]]*(len(mylist)-1), mylist[1:])
[((0, 0, 0), (1, 1, 1)), ((0, 0, 0), (2, 2, 2)), ((0, 0, 0), (3, 3, 3))]
A list comprehension is even simpler: 列表理解甚至更简单:
>>> [ (mylist[0], sublist) for sublist in mylist[1:] ]
[((0, 0, 0), (1, 1, 1)), ((0, 0, 0), (2, 2, 2)), ((0, 0, 0), (3, 3, 3))]
I don't think that zip
is necessary here. 我认为这里不需要
zip
。 A list comprehension will work fine: 列表理解将正常工作:
>>> mylist = [(0,0,0),(1,1,1),(2,2,2),(3,3,3)]
>>> [(mylist[0], x) for x in mylist[1:]]
[((0, 0, 0), (1, 1, 1)), ((0, 0, 0), (2, 2, 2)), ((0, 0, 0), (3, 3, 3))]
>>>
Using map: 使用地图:
map(lambda x:(mylist[0],x),mylist[1:])
Output: 输出:
[((0, 0, 0), (1, 1, 1)), ((0, 0, 0), (2, 2, 2)), ((0, 0, 0), (3, 3, 3))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.