切片从蟒蛇阵列奇/偶行最短的路? [英] Shortest way to slice even/odd lines from a python array?

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

问题描述

或者,更普遍的问题是,怎么给一个数组让每一个第n行,所以偶/奇你想跳过一条线,但在一般情况下,你希望得到每第n个线,跳过n-1个行

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

您可能知道正常的列表访问来获得项目,例如 L [2] 来获得的第三项。给两个数之间用冒号,您可以指定的范围的你想从列表中得到的。返回值是另一个列表。例如。 L [2:5] 为您提供了第三至第六项。您还可以通过可选的第三个数字,它指定了步长。默认步长是其中之一,这只是意味着的抓住每一个项目的(开始和结束索引之间)。

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

例如:

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

请参阅在Python教程 名单。

See lists in the Python tutorial.

如果你想获得每一个的 N -th 的列表元素(即不包括第一个元素),你就必须像切片 L [(N-1):: N]

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

例如:

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

如果您要包含的第一个元素,你只是做 L [:: N]

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

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

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