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?

Asked By: Brian

||

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.

Answered By: Eli Bendersky
>>> selected_value = [array[i] for i in position_to_select]
Answered By: kev

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.])
Answered By: eumiro
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.