小编典典

在元组列表列表中拆分元组列表

python

我有一个类似的元组列表:

[(1,a),(2,b), (1, e), (3, b), (2,c), (4,d), (1, b), (0,b), (6, a), (8, e)]

我想将其拆分为列表中每个“ b”的列表

[[(1,a),(2,b)], [(1, e), (3, b)], [(2,c), (4,d), (1, b)], [(0,b)], [(6, a), (8, e)]]

有什么pythonic的方法可以做到这一点吗?


阅读 211

收藏
2021-01-20

共1个答案

小编典典

my_list = [(1, "a"),(2, "b"), (1, "e"), (3, "b"), (2, "c"), (1, "b"), (0, "b")]
result, temp = [], []

for item in my_list:
    temp.append(item)
    if item[1] == 'b':
        result.append(temp)
        temp = []

if len(temp) > 0:
    result.append(temp)

print result
# [[(1, 'a'), (2, 'b')], [(1, 'e'), (3, 'b')], [(2, 'c'), (1, 'b')], [(0, 'b')]]
2021-01-20