繁体   English   中英

拆分元组列表列表中的元组列表

[英]split list of tuples in lists of list of tuples

我有一个元组列表,如:

[(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方式来做到这一点?

你可以使用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))
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')]]

我的解决方案,直接在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]

是我们将创建的子列表索引的元组:

[(-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')]]    

那这个呢?

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

纯迭代器解决方案:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM