在元组列表列表中拆分元组列表 [英] split list of tuples in lists of list of tuples
本文介绍了在元组列表列表中拆分元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类似的元组列表:
I have a list of tuples like:
[(1,a),(2,b), (1, e), (3, b), (2,c), (4,d), (1, b), (0,b), (6, a), (8, e)]
我想将其分成每个"b"的列表列表
I want to split it into list of lists at every "b"
[[(1,a),(2,b)], [(1, e), (3, b)], [(2,c), (4,d), (1, b)], [(0,b)], [(6, a), (8, e)]]
有什么Python方法可以做到这一点吗?
is there any pythonic way to do this?
推荐答案
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')]]
这篇关于在元组列表列表中拆分元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文