如果我有以下情况:
[(1,2),(2,3),(0,0),(4,0),(0,1),(3,9),(2,0),(2,4)]
我怎样才能把它分成:
[(1,2),(2,3)], [(0,1),(3,9)], [(2,4),]
每次我在索引 1 处看到一个 0 的元组时,例如 (1,0),我都会拆分列表。
如果我有以下情况:
[(1,2),(2,3),(0,0),(4,0),(0,1),(3,9),(2,0),(2,4)]
我怎样才能把它分成:
[(1,2),(2,3)], [(0,1),(3,9)], [(2,4),]
每次我在索引 1 处看到一个 0 的元组时,例如 (1,0),我都会拆分列表。
试试这个:
from itertools import groupby
x = [(1,2), (2,3), (0,0), (4,0), (0,1), (3,9), (2,0), (2,4)]
print [l for l in [list(group) for key, group in groupby(x, key=lambda k: k[1]==0)]
if l[0][1] != 0]
[OUT] [[(1,2), (2,3)], [(0,1), (3,9)], [(2,4)]]
它会生成一个列表,您可以遍历该列表以获取这些子列表。
它不是特别光滑,但你可以像这样循环它:
myList = [(1,2),(2,3),(0,0),(4,0),(0,1),(3,9),(2,0),(2,4)]
groupedList = []
subList = []
for tup in myList:
if tup[1] == 0:
if subList != []:
groupedList.append(subList)
subList = []
else:
subList.append(tup)
if subList != []:
groupedList.append(subList)
print groupedList
输出:
[[(1, 2), (2, 3)], [(0, 1), (3, 9)], [(2, 4)]]