I have an array a = [[1,1],[2,2],[3,3]]. How could I reduce it to b = [1,2,3]?
Asked
Active
Viewed 102 times
-4
-
1Are the values in the inner lists always identical? i.e. `[x, x]`? If yes, why do you even have a nested list like that? – Aran-Fey Oct 21 '18 at 17:47
-
1How exactly do you want it to be reduced? Say you had a list `a = [[1, 2], [3, 4], [5, 6]]`, or perhaps `[[1, 2], [3], [5, 4]]`. Would you want out of these `[1, 3, 5]`, or something else? – Oct 21 '18 at 17:47
-
...if so, then the [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) `[inner_list[0] for inner_list in a]` will do the trick, but I don't know if that is indeed what you want. – Oct 21 '18 at 17:48
-
1the elements are always the same – Adath Skyderson Oct 21 '18 at 17:48
-
a = [a[i][0] for i in range(len(a))] – Rarblack Oct 21 '18 at 18:16
-
`np.array(a)[:, 0]` – Shivid Oct 22 '18 at 08:47
1 Answers
2
If the inner array is always two of the same values.
a = [[1,1],[2,2],[3,3]]
b = [i for i,j in a]
This produces:
b = [1,2,3]

Christian Sloper
- 7,440
- 3
- 15
- 28
-
2And if the inner lists can be of different lengths (but can't be empty): `[head for head, *tail in a]`. This is especially useful for lists of generic iterables. If the elements are indexable, just `[sub[0] for sub in a]` should do. – timgeb Oct 21 '18 at 17:54
-
1