【问题标题】:How to index two elements from a Python list?如何索引 Python 列表中的两个元素?
【发布时间】:2021-04-13 18:52:08
【问题描述】:

为什么我不能为多个乱序索引位置索引一个 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()

【问题讨论】:

  • 单独访问每个元素。 mylist[0], mylist[2]
  • TypeError 告诉我们索引列表时允许的内容。这是基本的 Python!字符串、元组和字典也是如此。使用列表或元组选择多个项目是numpy 加法。每个可索引类都有一个__getitem__ 方法。允许的索引由该方法确定,因此可以不同。
  • @JohnGordon 个别元素是不是的问题。多个是
  • 但是@JohnGordon 是对的。您必须单独访问列表元素。没有办法解决这个问题。甚至maplist comprehension 也建议这样做。 array 往返会很慢。
  • 我现在明白他在暗示什么,但可以说

标签: python list numpy indexing element


【解决方案1】:

使用list comprehension:

print([mylist[i] for i in [0, 2]])
# ['apple', 'shirt']

或者使用numpy.array:

import numpy as np
print(np.array(mylist)[[0, 2]])
# ['apple', 'shirt']

【讨论】:

    【解决方案2】:

    使用Extended Slices:

    mylist = ['apple','guitar','shirt']
    print(mylist[::2])
    #Output: ['apple', 'shirt']
    

    【讨论】:

    • 适用于样本数据,但可能不是 OP 想要的。
    【解决方案3】:

    Python 列表仅支持整数和切片作为索引。 python的标准切片规则如下:

    i:j:k 在方括号内,用于访问多个元素。 其中i 是起始索引,j 是结束索引,k 是步骤。

    >>> list_ =  ['apple','guitar','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]
    

    【讨论】:

    • i:j:k 仅适用于固定步数/增量。寻找可以灵活地允许手动索引列表位置的东西,例如0, 2, 7, 6, 5, 21
    • 如果不想使用NumPy,那么map()函数是最好的方法。
    • 我用 map 函数的例子更新了我上面的答案,只需将 __getitem__ 映射到 index 列表。
    【解决方案4】:

    我的建议是:使用 NumPy 库(将 numpy 导入为 np)。它将允许您创建一个比标准列表具有优势的 numpy 数组。使用 numpy 数组,您将能够通过称为 Fancy Indexing 的过程访问任意数量的项目。

    mylist[0] returns 'apple'
    

    问题描述中可用的上述代码/语句描述了 Python 程序员执行索引 - 这是传递单个项目的索引位置以检索项目的过程 - 但是如果需要多个项目,这将是困难的/不可能的。

    import numpy as np #import the numpy package
    
    mylist = np.array(['apple','guitar','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'。 (零索引)。请注意,我们传入了列表中所需元素的索引位置。因此,我们不是返回一个元素,而是返回两个(或任意数量)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-23
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      相关资源
      最近更新 更多