根据元组内的值拆分元组列表

时间:2012-11-10 23:28:46

标签: python

如果我有以下内容:

[(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的元组时,例如(1,0),我拆分了清单。

2 个答案:

答案 0 :(得分:7)

试试这个:

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)]]

它生成一个列表,您可以迭代以获取这些子列表。

答案 1 :(得分:2)

它不是特别光滑,但你可以像这样循环它:

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)]]