Why can't I get two lists from one list comprehension?

So, I have an array of the following form:

[(1, u'first_type', u'data_gid_1'), 
 (2, u'first_type', u'data_gid_2'), 
 (3, u'first_type', u'data_gid_3'), 
 (4, u'first_type', u'data_gid_4')]

Now I want to extract the first and last elements of each internal list into separate lists. Therefore, if I do this:

>>> ids = [dat[0] for dat in all_data]
>>> gds = [dat[2] for dat in all_data]

It works as I expect. However, I tried to combine these two into one call, something like:

 (ids, gds) = [(dat[0], dat[2]) for dat in all_data]

This, however, fails:    ValueError: too many values to unpack

So can someone explain why this is happening, and if what I'm trying to do is even possible.

Regards, Bogdan

+5
source share
4 answers

This does not work because the length [(dat[0], dat[2]) for dat in all_data]matches the length all_data, which is not the same length as the tuple (ids, gds).

Try this instead:

(ids, gds) = zip(*[(dat[0], dat[2]) for dat in all_data])

or even shorter:

(ids, gds) = zip(*all_data)[::2]

, ids gds , , , :

(ids, gds) = map(list, zip(*all_data)[::2])



zip(*something) - python. ,

l = [[1, 2, 3],
     [4, 5, 6]]

zip(*l) :

zip(*l) == [(1, 4),
            (2, 5),
            (3, 6)]

* : some_func(*some_list) some_list, some_list . , zip(*l) zip([1, 2, 3], [4, 5, 6]). python.

zip zipper, , , : , ..

+8

:

data = [(1, u'first_type', u'data_gid_1'), 
 (2, u'first_type', u'data_gid_2'), 
 (3, u'first_type', u'data_gid_3'), 
 (4, u'first_type', u'data_gid_4')]

ids, gds = ([row[i] for row in data] for i in [0,2])
+4

[(dat[0], dat[2]) for dat in all_data] , (dat[0],dat[2]). , : d[0] d[2].

You can just use zip, but this will result in tuples. If you need lists, you need to apply listto the result:

(ids, gds) = map(list,zip(*[(dat[0], dat[2]) for dat in a]))
+1
source

Since you are creating two separate lists, try the following:

ids, dgs = [(dat[0]) for dat in all_data], [(dat[2]) for dat in all_data]

or you can unzip it into a single list using the command you used:

x = [(dat[0], dat[2]) for dat in all_data]
0
source

All Articles