简体   繁体   中英

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

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.

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