Select arrays from a list
Question:
I work with python and I have a really basic question.
I an array of 1000 elements. I want to select 100 positions of this array.
I want to do something like
selected_value=array[i for i in position_to_select]
How can I make this work?
Answers:
Suppose you have the list arr
, from which you want to select elements at positions 0, 4, 2:
>>> arr = [1, 2, 3, 4, 5, 6, 7]
>>> selected = [arr[i] for i in [0, 4, 2]]
>>> selected
[1, 5, 3]
>>>
I think that the key difference with your original code sample is using arr[i]
in the list comprehension. A list comprehension creates a new list. It is not used to index an existing list.
>>> selected_value = [array[i] for i in position_to_select]
If you work often with large arrays, have a look at numpy:
import numpy as np
arr = np.array([3., 4., 3., 7., 3., 6., 9., 1., 2., 5.])
position_to_select = [1, 3, 6]
selected_value = arr[position_to_select]
# array([ 4., 7., 9.])
I work with python and I have a really basic question.
I an array of 1000 elements. I want to select 100 positions of this array.
I want to do something like
selected_value=array[i for i in position_to_select]
How can I make this work?
Suppose you have the list arr
, from which you want to select elements at positions 0, 4, 2:
>>> arr = [1, 2, 3, 4, 5, 6, 7]
>>> selected = [arr[i] for i in [0, 4, 2]]
>>> selected
[1, 5, 3]
>>>
I think that the key difference with your original code sample is using arr[i]
in the list comprehension. A list comprehension creates a new list. It is not used to index an existing list.
>>> selected_value = [array[i] for i in position_to_select]
If you work often with large arrays, have a look at numpy:
import numpy as np
arr = np.array([3., 4., 3., 7., 3., 6., 9., 1., 2., 5.])
position_to_select = [1, 3, 6]
selected_value = arr[position_to_select]
# array([ 4., 7., 9.])