问题描述
为什么我无法为多个乱序索引位置索引 Python 列表?
mylist = ['apple','guitar','shirt']
mylist[0]
返回 'apple'
,但 mylist[0,2]
返回 TypeError: list indices must be integers or slices,not tuple
到目前为止,只有看起来很忙的方法才有效:
np.asarray(mylist)[[0,2]].tolist()
解决方法
print([mylist[i] for i in [0,2]])
# ['apple','shirt']
或者使用numpy.array
:
import numpy as np
print(np.array(mylist)[[0,'shirt']
,
mylist = ['apple','guitar','shirt']
print(mylist[::2])
#Output: ['apple','shirt']
,
Python 列表仅支持整数和切片作为索引。 python的标准切片规则如下:
i:j:k
位于方括号内,用于访问多个元素。
其中 i
是起始索引,j
是结束索引,k
是步骤。
>>> list_ = ['apple','shirt']
>>> mylist[0:2]
['apple','guitar']
如果你想根据某些特定索引获得一些随机元素,那么使用 List Comprehension
或只是一个 for
循环
还有另一种方法可以使用 map()
函数访问某些索引中的项目。
>>> a_list = [1,2,3]
>>> indices_to_access = [0,2]
>>> accessed_mapping = map(a_list.__getitem__,indices_to_access)
>>> accessed_list = list(accessed_mapping)
>>> accessed_list
[ 1,3]
,
我的建议是:使用 NumPy 库(将 numpy 导入为 np)。它将允许您创建一个比标准列表具有优势的 numpy 数组。使用 numpy 数组,您将能够通过称为 Fancy Indexing 的过程访问任意数量的项目。
mylist[0] returns 'apple'
问题描述中可用的上述代码/语句描述了一个 Python 程序员执行索引 - 这是传递单个项目的索引位置以检索项目的过程 - 但是在需要多个项目的情况下,这很困难/不可能。
import numpy as np #import the numpy package
mylist = np.array(['apple','shirt']) #create the numpy array
mylist[[0,2]] #return the first and third items ONLY. (zero-indexed)
Out[11]: array(['apple','shirt'],dtype='<U6')
如果您在 python 中使用 NumPy 库(见上图),您将能够创建一个 NumPy 数组,它允许在您的数组上执行更多方法和操作。
与仅返回单个/单个项目的 mylist[0]
相比,我们使用 mylist[[0,2]]
向 python 编译器指定我们希望从列表中准确检索两个元素,这些元素位于索引位置“0”和“2”。 (零索引)。请注意,我们传入了列表中所需元素的索引位置。因此,我们不返回一个元素,而是返回两个(或您想要的任意多个)。