0

Given array=[1, 2, 3, 4, 5, 6]

I want to choose the 0-th 2-nd, 4-th index value to build a new array

array1=[1, 3, 5]

Could someone show me how to do using python? Thanks~

2 Answers 2

6

If it is just 0, 2, and 4, you can use operator.itemgetter():

from operator import itemgetter

array1 = itemgetter(0, 2, 4)(array)

That will be a tuple. If it must be a list, convert it:

array1 = list(itemgetter(0, 2, 4)(array))

If the point is to get the even numbered indices, use slicing:

array1 = array[::2]

Whichever you are looking for, you could use a list comprehension:

array1 = [array[i] for i in (0, 2, 4)]

or

array1 = [array[i] for i in xrange(0, len(array), 2)]
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks very much~ If I want to set the "step",which is the picking interval, how could I do? For example, I want to pick elements at 0,3,6 indices or 0,4,8~
@Echo0831, you can achieve that by writing array1 = [array[i] for i in xrange(start, len(array), step)], where start should be the index of the first element and step is the step size. Or you can see my answer.
@Echo0831: When I say array[::2], that means all items in array from one end to the other with a step of 2. Therefore, you can just change the 2 to whatever step you want. In array1 = [array[i] for i in xrange(0, len(array), 2)], I say to go from an index of 0, the first element, to the index of the length of the array - 1, the last element, with a step of 2. Therefore, you can change the 2 to whatever step you want.
0

You can try something like this. In python the nth term of a list has index (n-1). Suppose the first element you want is 2, which happens to be the element 1 of array. Just save the first element index in a variable. Append it to the new list array1 and increase the index by 2. Continue doing this until the list array is exhausted.

from numpy import*
array=[1,2,3,4,5,6]
array1=[]
term=1
while term<len(array):   # if the array length is 6 then it will have upto element 5.
    array1.append(array[term])
    term=term+2          # 2 is the gap between elements. You can replace it with your required step size.

1 Comment

Got you! make sense~

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.