【问题标题】:Python list as a list indicesPython 列表作为列表索引
【发布时间】:2013-03-30 16:58:06
【问题描述】:

假设我们有两个列表

list_A = [1,3,4,54,3,5,6,2,6,77,73,39]
list_B = [0,3,2,8]

我想访问以list_B 中的值作为索引的list_A 元素(不使用循环)。

执行后,对于上述情况,结果应该如下:

[1, 54, 4, 6]

是否有任何简单的方法可以做到这一点,而无需担心for 循环(在代码中显式调用它)?

【问题讨论】:

  • 如果您要走 numpy 路径,则略有相关:stackoverflow.com/questions/7002895/numpy-array-indexing
  • 这完全取决于for-loop 的含义。显而易见的方法是使用列表理解。 [A[x] for x in B] 是否使用 for-loop?也许。 map(lambda i: list_A[i], list_B) 吗?看不到for-loop,但map 中有迭代。 numpy 解决方案怎么样?没有可见的迭代,但是...

标签: python list


【解决方案1】:

如果您使用的是 numpy,您可以执行以下操作:

list_A[list_B]  // yields [1, 54, 4, 6]

编辑:正如 Nick T 指出的,不要忘记先转换为数组!

【讨论】:

  • 在这样做之前应该将列表转换为数组,对吧?
  • list_A 应该是。 list_B 不一定是。 arr_A = np.array(list_A)
【解决方案2】:

一切都会在内部使用循环*,但它不必像您想象的那么复杂。您可以尝试列表理解:

[list_A[i] for i in list_B]

或者,您可以使用operator.itemgetter

list(operator.itemgetter(*list_B)(list_A))

>>> import operator
>>> list_A = [1,3,4,54,3,5,6,2,6,77,73,39]
>>> list_B = [0,3,2,8]
>>> [list_A[i] for i in list_B]
[1, 54, 4, 6]
>>> list(operator.itemgetter(*list_B)(list_A))
[1, 54, 4, 6]

* 好的!也许你不需要一个带有递归的循环,但我认为这样的事情肯定是矫枉过正。

【讨论】:

  • 使用循环。但是不使用循环的要求太疯狂了。
  • @MartijnPieters 一切的核心都将使用循环。
  • @A.R.S.:当然,numpy 解决方案在内部也使用循环。正如我所说,上述要求是无法实现的。
  • 我的意图不是显式调用循环。谢谢。
  • @A.R.S.:“……除非它使用递归。”
【解决方案3】:

递归答案

这里没有迭代/循环。只是递归。

>>> list_A = [1,3,4,54,3,5,6,2,6,77,73,39]
>>> list_B = [0,3,2,8]
>>> def foo(src, indexer):
...     if not indexer:
...         return []
...     else:
...         left, right = indexer[0], indexer[1:]
...         return [src[left]] + foo(src, right)
... 
>>> foo(list_A, list_B)
[1, 54, 4, 6]

【讨论】:

    【解决方案4】:

    地图答案

    >>> list_A = [1,3,4,54,3,5,6,2,6,77,73,39]
    >>> list_B = [0,3,2,8]
    >>> map(lambda i: list_A[i], list_B)
    [1, 54, 4, 6]
    

    免责声明

    我认为这在技术上不符合没有for-loop 的要求。

    【讨论】:

      【解决方案5】:

      Numpy 可以通过its indexing 以相当直接的方式做到这一点。将列表转换为数组,然后你就是黄金。您可以将任何类型的可迭代作为索引传递。

      >>> import numpy
      >>> list_A = [1,3,4,54,3,5,6,2,6,77,73,39]
      >>> list_B = [0,3,2,8]
      >>> numpy.array(list_A)[list_B]
      array([ 1, 54,  4,  6])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-12
        • 1970-01-01
        • 1970-01-01
        • 2015-04-25
        • 1970-01-01
        • 2019-07-05
        • 2018-11-13
        • 1970-01-01
        相关资源
        最近更新 更多