Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most pythonic way to convert a list of tuples

I need to convert a list of tuples in the style:

[(day1, name1, value1), (day2, name2, value2), (day3, name3, value3)]... etc

into:

[day1, day2, day3], [name1, name2, name3], [value1, value2, value3]... etc

Currently I'm doing it like this:

vals is the list of tuples
day = []
name = []
value = []
for val in vals:
    day.append(val[0])
    name.append(val[1])
    value.append(val[2])

It works, but it looks pretty ugly... I'm wondering if there's a more "pythonic" way to achieve the same result

like image 313
Augusto Dias Noronha Avatar asked Dec 26 '22 21:12

Augusto Dias Noronha


1 Answers

A list comprehension with the zip() function is easiest:

[list(t) for t in zip(*list_of_tuples)]

This applies each separate tuple as an argument to zip() using the *arguments expansion syntax. zip() then pairs up each value from each tuple into new tuples.

Demo:

>>> list_of_tuples = [('day1', 'name1', 'value1'), ('day2', 'name2', 'value2'), ('day3', 'name3', 'value3')]
>>> [list(t) for t in zip(*list_of_tuples)]
[['day1', 'day2', 'day3'], ['name1', 'name2', 'name3'], ['value1', 'value2', 'value3']]

This forces the output to use lists; you can just use straight zip() if all you need is the 3-value combos:

>>> zip(*list_of_tuples)
[('day1', 'day2', 'day3'), ('name1', 'name2', 'name3'), ('value1', 'value2', 'value3')]

In Python 3, use list(zip(*list_of_tuples)) or just loop over the output.

like image 191
Martijn Pieters Avatar answered Dec 30 '22 16:12

Martijn Pieters