从python数组切片偶数/奇数行的最短方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4988002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Shortest way to slice even/odd lines from a python array?
提问by fatcat
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.
或者,一个更普遍的问题是,如何对数组进行切片以获得第 n 行,因此对于偶数/奇数,您希望跳过一行,但在一般情况下,您希望得到每个 n- th 行,跳过 n-1 行。
采纳答案by Felix Kling
Assuming you are talking about a list, you specify the step in the slice (and start index). The syntax is list[start:end:step].
假设你在谈论一个list,你指定切片中的步骤(和开始索引)。语法是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 rangethat 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).
您可能知道获取项目的正常列表访问权限,例如l[2]获取第三个项目。给出两个数字和中间的冒号,您可以指定要从列表中获取的范围。返回值是另一个列表。例如,l[2:5]给你第三到第六项。您还可以传递可选的第三个数字,用于指定步长。默认步长为 1,这意味着获取每个项目(在开始和结束索引之间)。
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.
请参阅Python 教程中的列表。
If you want to get every n-thelement of a list (i.e. excluding the first element), you would have to slice like l[(n-1)::n].
如果要获取列表的每个n第 -th 个元素(即不包括第一个元素),则必须像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].
如果要包含第一个元素,只需执行l[::n].
回答by ajmartin
> map(lambda index: arr[index],filter(lambda x: x%n == 0,range(len(arr))))
where arris a list, and nslices are required.
wherearr是一个列表,并且n需要切片。
回答by delijati
This is more for 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]

