python - Get ith, jth and kth elements of a tuple in respective lists

Viewed 187

I have a tuple with data like

results = ((a, b, c, d), (1, 2, 3, 4), (q, w, e, r))

I need 1st, 2nd and 3rd element in different lists like:

one = [a, 1, q]
two = [b. 2, w]
thr = [c, 3, e]

I am doing it like:

one = [r[0] for r in results]
two = [r[1] for r in results]
thr = [r[2] for r in results]

But I feel there would be a way to do this in a single line instead of three loops.

Other way I could think of is like

 for r in results:
    one.append(r[0])
    two.append(r[1])
    thr.append(r[2])

Is there any other better solution?

3 Answers

You could use zip for this:

>>> for (one, two, thr) in zip(*results):
...   print (one, two, thr)
... 
a 1 q
b 2 w
c 3 e
d 4 r

If you are dealing with jagged lists and care about elements at the ends of the longer lists you should look at zip_longest in the itertools module. It will produce similar results with a fill value (default of None) for the shorter lists.

You can zip the sequence of tuples and then unpack the output of zip into separate variables:

one, two, thr, *_ = zip(*results)

so that:

print(one, two, thr, sep='\n')

outputs:

('a', '1', 'q')
('b', '2', 'w')
('c', '3', 'e')

If you need the resulting variables as lists instead you can map the output of zip to the list constructor:

one, two, thr, *_ = map(list, zip(*results))

so that:

print(one, two, thr, sep='\n')

outputs:

['a', '1', 'q']
['b', '2', 'w']
['c', '3', 'e']

You can also use list comprehension this way

r = [[el[i] for el in results] for i in range(len(results))]

This give you a list of the list you want. Output :

[['a', 1, 'q'], ['b', 2, 'w'], ['c', 3, 'e']]
Related