gpt4 book ai didi

Python 列表作为列表索引

转载 作者:太空宇宙 更新时间:2023-11-04 06:48:52 24 4
gpt4 key购买 nike

假设我们有两个列表

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

我想访问 list_A 的元素,这些元素将 list_B 中的值作为它们的索引(不使用循环)。

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

[1, 54, 4, 6]

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

最佳答案

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

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

* 好的!也许您不需要带递归的循环,但我认为对于这样的事情来说它肯定是过大了。

关于Python 列表作为列表索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15721079/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com