Jane_Tandert
Jane_Tandert

Reputation: 17

Join a list of tuples

My code looks the following:

from itertools import groupby

for key, group in groupby(warnstufe2, lambda x: x[0]):

    for element in group:
        a = element[1:4]
        b = element[4:12]
        c = [a,b]
        print(c)

When I print (c) I get something like this:

[(a,b,c),(d,e,f)] 
[(g,h,i),(j,k,l)]

where a1=(a,b,c) and b1=(d,e,f) and a2=(g,h,i) and b2 = (j,k,l). Of course there is a3... and b3... However, I need something like this:

[(a,b,c),(d,e,f),(g,h,i),(j,k,l)]

I already tried a for loop through c:

for item in c:
    list1 = []
    data = list1.append(item)

But this did not help and resulted in:

None
None

based on this link: https://mail.python.org/pipermail/tutor/2008-February/060321.html

I appears to be easy, but I am new to python and did not find a solution yet, despite a lot of reading. I appreciate your help!

Upvotes: 0

Views: 776

Answers (2)

Chetchaiyan
Chetchaiyan

Reputation: 271

Try This

from itertools import groupby

result = []
for key, group in groupby(warnstufe2, lambda x: x[0]):
    for element in group:
        a = element[1:4]
        b = element[4:12]
        c = [a,b]
        result.append(c)

print (result)

Upvotes: 0

Lukas Graf
Lukas Graf

Reputation: 32580

Use itertools.chain() and list unpacking:

>>> items = [[('a','b','c'),('d','e','f')], [('g','h','i'),('j','k','l')]]
>>>
>>> list(chain(*items))
[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'h', 'i'), ('j', 'k', 'l')]

Upvotes: 5

Related Questions