Shortest way to cut even / odd lines from python array?

Or, a more general question: how to cut an array to get every nth row, so for odd / even you want to skip one row, but in the general case you want to get every nth row, skipping n-1 rows.

+50
python arrays
Feb 14 2018-11-11T00:
source share
3 answers

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

You probably know access to regular lists to get an item, for example. l[2] to get the third element. By providing two numbers and a colon between them, you can specify the range that you want to get from the list. The return value is a different list. For example. l[2:5] gives you the third to sixth element. You can also pass in an additional third number, which determines the step size. The default step size is one, which means only each element (between the 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 the listings in the Python tutorial .

If you want to get every n th element of the list (that is, excluding the first element), you need to chop 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, every third element will look like this:

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

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

+106
Feb 14 2018-11-11T00:
source share

This is more to me as a complete example;)

 >>> import itertools >>> ret = [[1,2], [3,4,5,6], [7], [8,9]] >>> itertools.izip_longest(*ret) >>> [x for x in itertools.chain.from_iterable(tmp) if x is not None] [1, 3, 7, 8, 2, 4, 9, 5, 6] 
+1
Sep 11 '13 at 10:37
source share
 > map(lambda index: arr[index],filter(lambda x: x%n == 0,range(len(arr)))) 

where arr is the list and n are the fragments.

-2
Feb 14 2018-11-11T00:
source share



All Articles