如何从Python中的数组中获取第1,第3和第5个元素?

use*_*465 2 python arrays list

有没有一种快速的方法从Python中的数组中获取第1,第3和第5个元素,如[0,2,4]?谢谢.

fal*_*tru 6

使用operator.itemgetter:

>>> lst = [1,2,3,4,5,6,7]
>>> import operator
>>> get135 = operator.itemgetter(0, 2, 4)
>>> get135(lst)
(1, 3, 5)
Run Code Online (Sandbox Code Playgroud)


Ale*_*ton 5

您可以这样做,这是一个不需要导入的简单方法:

>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> [a[i] for i in (0, 2, 4)]
[1, 3, 5]
Run Code Online (Sandbox Code Playgroud)