day
day

Reputation: 93

list method to group elements in Python

Thanks for all your answers but I edit my question because it was not clear for all. I have the following list of tuples:

[("ok",1),("yes",1),("no",0),("why",1),("some",1),("eat",0),("give",0),("about",0),("tell",1),("ask",0),("be",0)]

I would like to have :

[("ok yes","no"),("why some","eat give about"),("tell","ask be")]

Thank you !

So I want to regroup all 1 and when a 0 appears I add the value in my list and I create a new element for the next values.

Upvotes: 1

Views: 82

Answers (3)

Ajax1234
Ajax1234

Reputation: 71451

You can use itertools.groupby:

from itertools import groupby
d = [("ok",1),("yes",1),("no",0),("why",1),("some",1),("eat",0),("give",0),("about",0),("tell",1),("ask",0),("be",0)]
new_d = [' '.join(j for j, _ in b) for _, b in groupby(d, key=lambda x:x[-1])]
result = [(new_d[i], new_d[i+1]) for i in range(0, len(new_d), 2)]

Output:

[('ok yes', 'no'), ('why some', 'eat give about'), ('tell', 'ask be')]

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195438

One possible solution using itertools.groupby:

from operator import itemgetter
from itertools import groupby

lst = [("ok",1), ("yes",1), ("no",0), ("why",1), ("some",1), ("eat",0)]

def generate(lst):
    rv = []
    for v, g in groupby(lst, itemgetter(1)):
        if v:
            rv.append(' '.join(map(itemgetter(0), g)))
        else:
            for i in g:
                rv.append(i[0])
                yield tuple(rv)
                rv = []
    # yield last item if==1:
    if v:
        yield tuple(rv)

print([*generate(lst)])

Prints:

[('ok yes', 'no'), ('why some', 'eat')]

Upvotes: 0

Kapil
Kapil

Reputation: 917

As per my understanding following code should work for your above question

list_tuples = [("ok",1),("yes",1),("no",0),("why",1),("some",1),("eat",0)]

tups=[]
updated_list=[]
for elem in list_tuples:
        if elem[1] == 0:
                updated_list.append(tuple([' '.join(tups), elem[0]]))
                tups=[]
        else:
                tups.append(elem[0])

print updated_list

Upvotes: 1

Related Questions