【问题标题】:In Python, how do I index a list with another list?在 Python 中,如何用另一个列表索引一个列表?
【发布时间】:2010-11-03 23:22:31
【问题描述】:

我想用另一个这样的列表索引一个列表

L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Idx = [0, 3, 7]
T = L[ Idx ]

并且 T 最终应该是一个包含 ['a', 'd', 'h'] 的列表。

有没有更好的办法

T = []
for i in Idx:
    T.append(L[i])

print T
# Gives result ['a', 'd', 'h']

【问题讨论】:

  • L[idx] 不仅仅在基础 Python 中工作,这真的很奇怪。蟒蛇之禅等等。在 numpy 中,类似这样的工作就可以了。
  • @eric numpy 数组与 CPython 列表对象大不相同

标签: python list indexing


【解决方案1】:

我的问题:查找列表的索引。

L = makelist() # Returns a list of different objects
La = np.array(L, dtype = object) # add dtype!
for c in chunks:
    L_ = La[c] # Since La is array, this works.

【讨论】:

    【解决方案2】:

    您还可以将__getitem__ 方法与map 结合使用,如下所示:

    L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
    Idx = [0, 3, 7]
    res = list(map(L.__getitem__, Idx))
    print(res)
    # ['a', 'd', 'h']
    

    【讨论】:

      【解决方案3】:
      L= {'a':'a','d':'d', 'h':'h'}
      index= ['a','d','h'] 
      for keys in index:
          print(L[keys])
      

      我会使用Dict add 所需的keysindex

      【讨论】:

        【解决方案4】:

        函数式方法:

        a = [1,"A", 34, -123, "Hello", 12]
        b = [0, 2, 5]
        
        from operator import itemgetter
        
        print(list(itemgetter(*b)(a)))
        [1, 34, 12]
        

        【讨论】:

        • 如果b 恰好只包含一项,这将不起作用。
        【解决方案5】:

        我对这些方法中的任何一种都不满意,所以我想出了一个Flexlist 类,它允许通过整数、切片或索引列表进行灵活的索引:

        class Flexlist(list):
            def __getitem__(self, keys):
                if isinstance(keys, (int, slice)): return list.__getitem__(self, keys)
                return [self[k] for k in keys]
        

        对于您的示例,您将用作:

        L = Flexlist(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
        Idx = [0, 3, 7]
        T = L[ Idx ]
        
        print(T)  # ['a', 'd', 'h']
        

        【讨论】:

        • 这也展示了 Python 的强大和灵活性!
        • 对现有代码进行扩展非常容易。只需拨打existing_list = Flexlist(existing_list),我们就拥有所需的功能而不会破坏任何代码
        • 我改为使用self[int(k)],这样我也可以使用np.arrays 作为索引。否则,你会得到一个np.int64 is not iterable 错误。
        【解决方案6】:

        如果你使用的是 numpy,你可以像这样执行扩展切片:

        >>> import numpy
        >>> a=numpy.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
        >>> Idx = [0, 3, 7]
        >>> a[Idx]
        array(['a', 'd', 'h'], 
              dtype='|S1')
        

        ...而且可能要快得多(如果性能足以影响 numpy 导入)

        【讨论】:

        • 我的快速 timeit 测试表明,使用 np.array 实际上慢了近 3 倍(包括转换为数组)。
        • 如果您需要将其转换为数组操作,它会更好。常规列表操作太耗时。
        • 我尝试了这种方法,即将list 替换为np.array,但是当元素本身是锯齿状数组时,np.append 无法正常工作(即与列表相同的结果)。跨度>
        【解决方案7】:
        T = map(lambda i: L[i], Idx)
        

        【讨论】:

        • 需要在py3k中转成list
        【解决方案8】:
        T = [L[i] for i in Idx]
        

        【讨论】:

        • 这比 for 循环更快还是更短?
        • @daniel:两者都推荐
        • 一个快速的计时测试(没有 pysco 或任何东西,所以随心所欲)显示列表理解比循环(1000 个元素,重复 10000 次)快 2.5 倍。
        • (使用 map 和 lambda 甚至更慢 - 意料之中,因为每次迭代都会调用一个函数)
        • +1 如果索引列表是任意的,那么列表组合就是方法。我认为,如果可能的话,这里似乎不是这种情况,切片会更快。
        猜你喜欢
        • 1970-01-01
        • 2018-04-02
        • 1970-01-01
        • 1970-01-01
        • 2018-07-15
        • 1970-01-01
        • 2014-12-21
        • 2023-01-02
        相关资源
        最近更新 更多