Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest way to slice even/odd lines from a python array?

Tags:

python

arrays

Or, a more general question would be, how to slice an array to get every n-th line, so for even/odd you'd want to skip one line, but in the general case you'd want to get every n-th lines, skipping n-1 lines.

like image 980
fatcat Avatar asked Feb 14 '11 00:02

fatcat


People also ask

Can you slice an array in Python?

Array slicing can be easily done following the Python slicing method. For which the syntax is given below. Again, Python also provides a function named slice() which returns a slice object containing the indices to be sliced. The syntax for using this method is given below.

How do you extract an odd number from an array in Python?

This Python Program uses the for loop range to Print the Odd Numbers in a Numpy Array. The if statement (if (oddArr[i] % 2 != 0)) checks the numpy array item at each index position is not divisible by two. If True, (print(oddArr[i], end = ” “)) print that numpy Odd array number.

How do you slice in Python?

Python slice() FunctionThe slice() function returns a slice object. A slice object is used to specify how to slice a sequence. You can specify where to start the slicing, and where to end. You can also specify the step, which allows you to e.g. slice only every other item.

How does slicing an array work in Python?

Slicing in python means taking elements from one given index to another given index. We pass slice instead of index like this: [start:end] . We can also define the step, like this: [start:end:step] .


1 Answers

Assuming you are talking about a list, you specify the step in the slice (and start index). The syntax is list[start:end:step].

You probably know the normal list access to get an item, e.g. l[2] to get the third item. Giving two numbers and a colon in between, you can specify a range that you want to get from the list. The return value is another list. E.g. l[2:5] gives you the third to sixth item. You can also pass an optional third number, which specifies the step size. The default step size is one, which just means take every item (between start and end index).

Example:

>>> l = range(10) >>> l[::2]         # even  - start at the beginning at take every second item [0, 2, 4, 6, 8] >>> l[1::2]        # odd - start at second item and take every second item [1, 3, 5, 7, 9] 

See lists in the Python tutorial.

If you want to get every n-th element of a list (i.e. excluding the first element), you would have to slice like l[(n-1)::n].

Example:

>>> l = range(20) >>> l [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] 

Now, getting every third element would be:

>>> l[2::3] [2, 5, 8, 11, 14, 17] 

If you want to include the first element, you just do l[::n].

like image 87
Felix Kling Avatar answered Sep 24 '22 04:09

Felix Kling