How to select Data by index in array

Question:

I have an array, in the array data it contains 89 values.

Data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86,
87, 88, 89]

from 89 values I only want to use some of the values from the array above like this Data : [17,19,20,21,40,45,54,65,74,77,82]. is it possible? if yes how I can implement it in code in python

Asked By: stack offer

||

Answers:

here’s the example of using lists comprehension:

data =  [1, 2, 3, 4, 5, 6, 7, 8, 9]

ids = [2, 4, 6] # ids of required values in the list (first element has 0 index)

result = [data[i] for i in ids] # new list with given values

print(result)
>>> [3, 5, 7]
Answered By: svfat

If you have 6 elements in:

Data=[1,2,3,8,9,10]

Then if you want to access any 3 elements of Data by index, you can do so by:

selected = Data[1,2,5] 
print(selected) #outputs: [2,3,10]
Answered By: Aswath

You can use numpy arrays, they can take a list of indexes and return exactly those elements. Try this:

import numpy as np
data = np.arange(1, 90) # Creates the array you wanted
indexes = [17, 19, 20, 21, 40, 45, 54, 65, 74, 77, 82]
print(data[indexes])

this will print

[18 20 21 22 41 46 55 66 75 78 83]

Note that lists and arrays are 0 indexed. Since your data starts with 1 at index 0, each element will have an index that is one less than the actual value in the list.

Answered By: Keinicke
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.