Is there a way to output multiple lists from a single list comprehension expression?

python

Solution

x, y = zip(*[d[:2] for d in data])

I think is what you want ... that will give you a list of x's and a list of y's

if each row in data only has d[0] and d[1] then you can just do

x1,x2,x3 = 1,2,3
y1,y2,y3 = 3,4,5
data = [(x1,y1),(x1,y2),(x3,y3)]
x,y = zip(*data)

if you have a dict

from operator import itemgetter
x,y,z = zip(*map(itemgetter('key1','key2','key3'),data))

if you wanted to apply a function you would need to do

x,y = zip(*[(function1(row['key']),function2(row['key2'])) for row in data])

Problem

Something like ``` x, y = [expression for d in data] ``` Basically I'd like to obtain the equivalent of this: ``` x = [] y = [] for d in data: x.append(d[0]) y.append(d[1]) ``` where `data` is a nested list? And what if data is a list of dictionaries? ``` x = [] y = [] for d in data: x.append(d['key1']) y.append(d['key2']) ``` And what if I want to apply a different function to each column where data is a list of dictionaries? ``` x = [] y = [] for d in data: x.append(func1(d['key1'])) y.append(func2(d['key2'])) ```

Original source