-1

I am very new to python, and just have a very simple question. I have a list which is replaced as:

x = [array([100., 100.]),
 array([119, 119]),
 array([143, 143]),
 array([171, 171]),
 array([204, 204])]

I want to create a list

b = [100, 119, 143, 171, 204]

I tried flatten but couldn't remove the same value and the 'array'. What should I do?

5 Answers5

0

I think you need 100 in your result. If that's the case, you can try below:

>>> list(set(array(x).flatten()))
[100.0, 171.0, 204.0, 143.0, 119.0]
Paras Gupta
  • 174
  • 4
0

Use np.concatenate with set

list(set(np.concatenate(x)))
Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55
0

I tried to reproduce your list first:

import numpy as np

x = [np.array([100., 100.]),
    np.array([119, 119]),
    np.array([143, 143]),
    np.array([171, 171]),
    np.array([204, 204])]

You can flatten your list using:

np.concatenate(x).ravel().tolist()

Output:

[100.0, 100.0, 119.0, 119.0, 143.0, 143.0, 171.0, 171.0, 204.0, 204.0]
0

So let me make sure I understood you properly, You have:

x = [array([100., 100.]), array([119, 119]), array([143, 143]), 
    array([171, 171]), array([204, 204])]

where x has 2 duplicate elements.

You want:

b = [100, 119, 143, 171, 204]

where b contains only the 1st (or 2nd) element of each array in x.

I believe there are libraries (itertools) to do this but here is a simple way you can implement quickly:

Method 1 (loop)

b = []

for arr in x:
    b.append(arr[0])

Method 2 (list comprehension)

b = [arr[0] for arr in x]
sourvad
  • 320
  • 1
  • 6
  • Thank you! yes that's what I want. And if I have a very long list (say 1000) containing arrays like above with 2 repeated values, will Method 1 change the order of the numbers in the output? – agneau1236 Mar 20 '21 at 18:35
  • No, neither method will change the order. Both are doing the exact same thing but method 2 is more concise to read. Both will iterate over "x" in the order of the elements in "x". Having more than 2 values in each array in "x" and the values being different will also not effect. However, make sure that all arrays in "x" are the same length, this is to avoid getting a 4th item from an array where no 4th item exists. – sourvad Mar 20 '21 at 18:36
0

first of all you have to convert the list to array and then slice the array like this

import numpy as np
b = np.array(x)
c = b[:,0]
print(c)

it give [100. 119. 143. 171. 204.]