Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get items from multidimensional list Python

Tags:

python

list

I have a list with the following appearance:

 [0] = [ [0.0, 100.0], [0.1, 93.08], [0.3, 92.85], [0.5, 92.62], [0.7, 91.12], [0.9, 90.89] ]

 [1] = [ [0.0, 100.0], [0.1, 2.79], [0.3, 2.62], [0.5, 2.21], [0.7, 1.83], [0.9, 1.83] ]

and I´d like to obtain vectors to plot the info as follows:

[0.0, 0.1, 0.3, 0.5, 0.7, 0.9]
[100.0, 93.08, 92.85, 92.62, 91.12, 90.89]

and the same with all entries in the list. I was trying something like:

x = mylist[0][:][0]

Any ideas? I appreciate the help!

like image 837
Slash Avatar asked Dec 05 '22 19:12

Slash


2 Answers

Use zip:

>>> mylist = [
    [0.0, 100.0], [0.1, 93.08], [0.3, 92.85], [0.5, 92.62],
    [0.7, 91.12], [0.9, 90.89] ]
>>> a, b = zip(*mylist)
>>> a
(0.0, 0.1, 0.3, 0.5, 0.7, 0.9)
>>> b
(100.0, 93.08, 92.85, 92.62, 91.12, 90.89)

>>> list(a)
[0.0, 0.1, 0.3, 0.5, 0.7, 0.9]
>>> list(b)
[100.0, 93.08, 92.85, 92.62, 91.12, 90.89]
like image 72
falsetru Avatar answered Dec 16 '22 07:12

falsetru


With pure-python you should use list-comprehension

data = [ [0.0, 100.0], [0.1, 93.08], [0.3, 92.85], [0.5, 92.62], [0.7, 91.12], [0.9, 90.89] ]
listx = [item[0] for item in data ]
listy = [item[1] for item in data ]

>>>listx
[0.0, 0.1, 0.3, 0.5, 0.7, 0.9]
>>>listy
[100.0, 93.08, 92.85, 92.62, 91.12, 90.89]

I think its a bit better than zip because it is easier to read and you do not have to cast the tuples

like image 26
JDurstberger Avatar answered Dec 16 '22 08:12

JDurstberger