从python数组中切片偶数/奇数行的最短方法? [英] Shortest way to slice even/odd lines from a python array?

查看:206
本文介绍了从python数组中切片偶数/奇数行的最短方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

或者,一个更普遍的问题是,如何对数组进行切片以获取每第 n 行,因此对于偶数/奇数,您希望跳过一行,但在一般情况下,您希望得到每第 n 行,跳过 n-1 行.

解决方案

假设您在谈论一个列表,您可以指定切片中的步骤(和开始索引).语法是list[start:end:step].

您可能知道获取项目的正常列表访问权限,例如l[2] 获取第三项.给出两个数字和中间的冒号,您可以指定要从列表中获取的范围.返回值是另一个列表.例如.l[2:5] 给你第三到第六项.您还可以传递可选的第三个数字,用于指定步长.默认步长为 1,这意味着获取每个项目(在开始和结束索引之间).

示例:

<预><代码>>>>l = 范围(10)>>>l[::2] # even - 从头开始​​,每隔一个项目取一次[0, 2, 4, 6, 8]>>>l[1::2] # 奇数 - 从第二个项目开始,每隔一个项目取一次[1, 3, 5, 7, 9]

请参阅Python 教程中的列表.

如果您想获取列表的每个 n-th 元素(即不包括第一个元素),则必须像 l[(n-1)::n].

示例:

<预><代码>>>>l = 范围(20)>>>升[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

现在,获取每三个元素将是:

<预><代码>>>>l[2::3][2, 5, 8, 11, 14, 17]

如果要包含第一个元素,只需执行 l[::n].

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.

解决方案

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].

这篇关于从python数组中切片偶数/奇数行的最短方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆