简体   繁体   中英

Python: Join lists of lists by the first element

I'm trying to combine a list of lists/tuples by the first element in the list - something like this:

Input:

[(1, [32, 432, 54]), (1, [43, 54, 65]), (2, [2, 43, 54]), (2, [1, 5, 6])]

Output:

[(1, [32, 432, 54], [43, 54, 65]), (2, [2, 43, 54], [1, 5, 6])]

The lists are actually ordered by the first element like in my example input, and it doesn't matter if at the end the tuples are lists.

Is there an efficient/pythonic way to do this?

Using itertools.groupby and list comprehension :

>>> lst = [(1, [32, 432, 54]), (1, [43, 54, 65]), (2, [2, 43, 54]), (2, [1, 5, 6])]
>>> import itertools
>>> [(key,) + tuple(v for k, v in grp)
...     for key, grp in itertools.groupby(lst, key=lambda x: x[0])]
[(1, [32, 432, 54], [43, 54, 65]), (2, [2, 43, 54], [1, 5, 6])]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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