简体   繁体   English

Python列表作为列表索引

[英]Python list as a list indices

Suppose we have two lists 假设我们有两个列表

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

I want to access elements of list_A that have the values in list_B as their indices (without using loops). 我想访问的元素list_A有中值list_B作为其索引(不使用循环)。

After implementing it, the result should be as follows for the above case: 实施后,上述情况的结果应如下所示:

[1, 54, 4, 6]

Is there any easy method to do this without bothering with for loops (calling it explicitly in the code) ? 有没有一种简单的方法可以做到这一点而无需打扰for循环(在代码中显式调用它)?

Everything will use a loop internally* 一切都将在内部使用循环* , but it doesn't have to be as complicated as you might think. ,但不必像您想象的那么复杂。 You can try a list comprehension: 您可以尝试列表理解:

[list_A[i] for i in list_B]

Alternatively, you could use operator.itemgetter : 或者,您可以使用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]

* OK! *好! Maybe you don't need a loop with recursion, but I think it's definately overkill for something like this. 也许您不需要使用递归循环,但是我认为对于这样的事情肯定是过大了。

Recursion answer 递归答案

No iteration/loops here. 这里没有迭代/循环。 Just recursion. 只是递归。

>>> 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]

map answer 地图答案

>>> 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]

Disclaimer 免责声明

I don't think this technically meets the requirement that there be no for-loop . 我认为这在技术上不符合没有for-loop

If you're using numpy, you can do the following: 如果您使用的是numpy,则可以执行以下操作:

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

Edit: As Nick T pointed out, don't forget to convert to arrays first! 编辑:正如Nick T所指出的,不要忘记先转换为数组!

Numpy can do this with its indexing in a fairly straightforward manner. Numpy可以通过相当直接的方式对其进行索引 Convert the list to an array then you're gold. 将列表转换为数组,那么您就是金。 You can pass any sort of iterable as indices. 您可以将任何可迭代的形式作为索引传递。

>>> 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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM