我有以下示例列表:
list_a = [(1, 6),
(6, 66),
(66, 72),
(72, 78),
(78, 138),
(138, 146),
(154, 208),
(208, 217),
(217, 225),
(225, 279),
(279, 288)
.....
]
我需要的是:
所以结果可能如下:
list_a = [(1, 6),
(6, 66),
(66, 72),
(72, 78),
(78, 138),
(138, 146),
(146, 1), # <- first part
(147, 154), # <- second part
(154, 208),
(208, 217),
(217, 225),
(225, 279),
(279, 288)
(288, 147) # <- first part
.....
]
我试过这个,但最后一个元素丢失了
for i in range(0, len(list_a)+1, 6):
if i > 0:
list_a.insert(i, (list_a[i - 1][1], list_a[i - 6][0]))
list_a.insert(i + 1, (list_a[i - 1][1] + 1, list_a[i + 1][0],))
答案 0 :(得分:2)
我只是通过不断追加而不是插入现有列表来构建新列表。这应该有效:
n = len(list_a)
newList = []
for i in range(0,n, 6):
newList.append(list_a[i:i+6] )
newTuple1 = (newList[-1][1], newList[i][0])
newList.append(newTuple1)
try:
newTuple2 = (newTuple1[0] + 1, list_a[i+6][0])
newList.append(newTuple2)
except IndexError:
print "There was no next tuple"
print newList
There was no next tuple
[(1, 6), (6, 66), (66, 72), (72, 78), (78, 138), (138, 146), (146, 1), (147, 154), (154, 208), (208, 217), (217, 225), (225, 279), (279, 288), (300, 400), (400, 146)]
请注意,如果没有其他元组,那么您的示例并未指明在第二种情况下要执行的操作。假设list_a中有12个元组。然后当你到达第二组2时,没有下一个元组。
希望有所帮助。