Get items from a multidimensional 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 would like to get vectors for constructing information 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 tried something like:

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

Any ideas? I appreciate the help!

+4
source share
4 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]
+8
source

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 this is a little better than zip because it is easier to read and you don't need to throw tuples

+5
source

numpy decision:

import numpy as np
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] ]
data_np = np.array(data)
a = data_np[:,0]
b = data_np[:,1]

In [126]: a
Out[126]: array([ 0. ,  0.1,  0.3,  0.5,  0.7,  0.9])

In [127]: b
Out[127]: array([ 100.  ,   93.08,   92.85,   92.62,   91.12,   90.89])
+1
source

You can also use map:

a = map(lambda x: x[0], your_list)
b = map(lambda x: x[1], your_list)
+1
source

Source: https://habr.com/ru/post/1623730/


All Articles