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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With