Domanda

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

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

is there any pythonic way to do this?

È stato utile?

Soluzione 2

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

Altri suggerimenti

You can use 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 solution, directly in the python console:

>>> 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 is the indices of the tuples with 'b', starting by -1.

[-1, 1, 3, 5, 6]

u is tuples of indices of the sublist that we will create:

[(-1, 1), (1, 3), (3, 5), (5, 6)]

And for the case not ending in a tuple with 'b':

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

gives:

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

What about this?

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

A pure iterator solution:

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)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top