我需要您的帮助,希望您能指出正确的方向,所以我得到了一个列表列表(这只是一个例子,列表列表可以包含更多元素),并且我试图在其中获取成对的元素列表
mylist = [[2, 3, 4], [2, 3]]
#desired output
# newlist = [[2,3], [3,4], [2,3]]
因此,在此问题中,它有助于创建一个元组列表,其中每个元组都是一对,因此我使用该问题的答案来创建此代码
mylist = [[2, 3, 4], [2, 3]]
coordinates = []
for i in mylist:
coordinates.append(list(map(list, zip(i, i[1:])))) #Instead of list of tuples, I use map to get a list of lists
print(coordinates)
#output [[[2, 3], [3, 4]], [[2, 3]]] #3D list but not exactly what I want
a = [e for sl in coordinates for e in sl] #Use list comprehension to transform the 3D list to 2D list
print(a)
#output [[2, 3], [3, 4], [2, 3]] #My desired output
使用这段代码,我得到了我想要的东西,但是我想知道是否有一种简单的方法可以在不创建大量辅助列表的情况下实现简单的列表理解呢?但是我不知道该怎么做,所以我们将不胜感激,谢谢!
尝试这个:
mylist = [[3, 2, 4, 3], [3, 3, 1], [2, 1]]
res = [x[idx: idx+2] for x in mylist for idx in range(0, len(x) - 1)]
print(res)
输出:
[[3, 2], [2, 4], [4, 3], [3, 3], [3, 1], [2, 1]]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句