0

I have a list of tuples (from prev. processing) that I want to assign column wise to new lists. I can do this on a column-by-column basis. But I was wondering if there was a smarter 1-line solution for it.

>>> lt= [(3.249, 0.5), (1.393, 0.55), (0.766, 0.6), (0.489, 0.66), (0.396, 0.7), (0.291, 0.78), (0.247, 0.84), (0.216, 0.9), (0.195, 0.96)]
>>> l0= [x[0] for x in lt]
>>> l1= [x[1] for x in lt]
>>> l0
[3.249, 1.393, 0.766, 0.489, 0.396, 0.291, 0.247, 0.216, 0.195]
>>> l1
[0.5, 0.55, 0.6, 0.66, 0.7, 0.78, 0.84, 0.9, 0.96]

I am looking for something like (pseudocode)

(l0,l1) = ([x[0] for x in lt],[x[1] for x in lt]

Your feedback is appreciated.

Gert Gottschalk
  • 1,658
  • 3
  • 25
  • 37

1 Answers1

1
l0,l1=zip(*lt)

Using zip you can achieve this.

l0,l1=map(list,zip(*lt)) # To get as list 
Smart Manoj
  • 5,230
  • 4
  • 34
  • 59
  • `l0,l1=list(zip(*lt))` can be just `l0, l1 = zip(*lt)` (the unpacking syntax already realizes the result, no need to listify it when the `list` will be thrown away immediately after construction). Similarly, the outermost parentheses around your `map` approach are completely superfluous (they don't do anything at all here). – ShadowRanger Feb 27 '18 at 01:06