且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用偶数和奇数索引将列表分成两半?

更新时间:2023-02-21 13:32:35

这应该可以为您提供所需的信息-定期从偏移量0或1采样列表:

This should give you what you need - sampling a list at regular intervals from an offset 0 or 1:

>>> a = ['blah', 3,'haha', 2, 'pointer', 1, 'poop', 'fire']
>>> a[0:][::2] # even
['blah', 'haha', 'pointer', 'poop']
>>> a[1:][::2] # odd
[3, 2, 1, 'fire']

请注意,在上面的示例中,第一个切片操作( a [1:] )演示了从所需起始索引中选择所有元素的方法,而第二个切片操作( a [::2]) 演示了如何选择列表中的所有其他项目.

Note that in the examples above, the first slice operation (a[1:]) demonstrates the selection of all elements from desired start index, whereas the second slice operation (a[::2]) demonstrates how to select every other item in the list.

一种更加惯用和高效的切片操作将两者合并为一个,即 a [:: 2] (可以省略 0 )和 a [1:: 2] ,它避免了不必要的列表复制,应该在生产代码中使用,就像其他人在评论中指出的那样.

A more idiomatic and efficient slice operation combines the two into one, namely a[::2] (0 can be omitted) and a[1::2], which avoids the unnecessary list copy and should be used in production code, as others have pointed out in the comments.