简体   繁体   English

Python使用其余元素压缩列表的第一个元素

[英]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.

相关问题 获取第一个元素作为索引以更新列表中元素的 rest - Get first element as index to update the rest of the elements within the list 如何将列表中的前三个元素作为列,其余作为行 - Python - How to make first three elements in a list as columns and the rest as rows - Python Python-传递带有元素的列表,但是我只获得列表中的第一个元素 - Python - Passing a list with elements, but I only get the first element in the list Python - 基于内部列表的第一个元素对列表列表中的元素求和 - Python - Summing elements on list of lists based on first element of inner lists 在Python中迭代列表中的连续元素,使最后一个元素与第一个元素组合 - Iterate consecutive elements in a list in Python such that the last element combines with first 在python列表中的第7个元素之后插入前7个元素的和 - insert sum of first 7 elements after 7th element in python list Python:按第一个元素对元素列表进行排序,但如果相等则按原始索引排序 - Python: Sort list of elements by first element, but if equal sort by original index 在列表python中将第一个元素移到最后一个元素之前 - Moving first elements before the last element in a list python 使用python将子列表中的第一个元素与同一列表中的元素合并 - Merging first element in sublist with elements in the same list using python 有没有办法在python中压缩列表/元组的内部元素? - Is there a way to zip inner elements of a list/tuple in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM