![](/img/trans.png)
[英]Get first element as index to update the rest of the elements within the list
[英]Python zip the first element of a list with the rest of elements
我有一份清單
mylist = [(0,0,0),(1,1,1),(2,2,2),(3,3,3)]
我希望找到一個代碼保存方法來將第一個元素mylist[0]
與列表元素mylist[1:]
的其余部分壓縮,以獲得一個新列表:
[((0,0,0),(1,1,1)),((0,0,0),(2,2,2)),((0,0,0),(3,3,3))]
使用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))]
列表理解甚至更簡單:
>>> [ (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))]
我認為這里不需要zip
。 列表理解將正常工作:
>>> 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))]
>>>
使用地圖:
map(lambda x:(mylist[0],x),mylist[1:])
輸出:
[((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.