我有一个元组列表,如:
[(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方法可以做到这一点?
答案 0 :(得分:3)
您可以使用yield
。
def get_groups(lst):
t = []
for i in lst:
t.append(i)
if i[1] == 'b':
yield t
t = []
if t:
yield t
my_list = [(1,a),(2,b), (1, e), (3, b), (2,c), (1, b), (0,b)]
groups = list(get_groups(my_list))
答案 1 :(得分: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')]]
答案 2 :(得分:1)
我的解决方案,直接在python控制台中:
>>> l = [(1,'a'),(2,'b'), (1, 'e'), (3, 'b'), (2,'c'), (1, 'b'), (0,'b')]
>>> b = [-1] + [x for x, y in enumerate(l) if y[1] == 'b' or x == len(l)-1]
>>> u = zip(b,b[1:])
>>> m = [l[x[0]+1:x[1]+1] for x in u]
>>> m
[[(1, 'a'), (2, 'b')], [(1, 'e'), (3, 'b')], [(2, 'c'), (1, 'b')], [(0, 'b')]]
b 是带有' b'的元组的索引,从-1开始。
[-1, 1, 3, 5, 6]
u 是我们将创建的子列表的索引元组:
[(-1, 1), (1, 3), (3, 5), (5, 6)]
对于没有以' b':
的元组结尾的情况[(1, 'a'), (2, 'b'), (1, 'e'), (3, 'b'), (2, 'c'), (1, 'b'), (0, 'b'), (6, 'a'), (8, 'e')]
给出:
[[(1, 'a'), (2, 'b')], [(1, 'e'), (3, 'b')], [(2, 'c'), (1, 'b')], [(0, 'b')], [(6, 'a'), (8, 'e')]]
答案 3 :(得分:1)
这个怎么样?
xs = [(1, 'a'), (2, 'b'), (1, 'e'), (3, 'b'), (2, 'c'), (4, 'd'), (1, 'b'), (0, 'b'), (6, 'a'), (8, 'e')]
result = [[]]
for x in xs:
result[0].append(x)
if x[1] == 'b':
result.insert(0, [])
result.reverse()
答案 4 :(得分:1)
纯粹的迭代器解决方案:
def get_groups(lst):
i = iter(lst)
def row(x):
while True:
yield x
if x[1] == 'b':
return
x = next(i)
for x in i:
yield row(x)
for r in get_groups(data):
print list(r)