Join a list of tuples

不想你离开。 提交于 2019-12-11 18:05:06

问题


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!


回答1:


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)



回答2:


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


来源:https://stackoverflow.com/questions/29415915/join-a-list-of-tuples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!