【问题标题】:Efficient way to return elements of a list using list of indices使用索引列表返回列表元素的有效方法
【发布时间】:2022-10-14 23:07:17
【问题描述】:
known_cards = self.hand[self.known_index]

最终给出错误

TypeError:列表索引必须是整数或切片,而不是列表

这里的输入将类似于以下内容

self.hand = [4,2,7,9]
self.known_index = [0,3]
known_cards = [4,9] # the 0th and 3rd index of self.hand

我知道使用循环会很容易解决,但是有没有更好的方法呢?

【问题讨论】:

标签: python


【解决方案1】:

known_cards = [ self.hand[idx] for idx in self.known_index]

在 Python 中,使用列表推导比循环更快

【讨论】:

    【解决方案2】:

    因此,您的代码中的问题是您正在传递一个列表来搜索列表中的索引值。这不能做,你可以这样做

    known_cards = [self.hand[index] for index in self.known_index]
    

    这使用列表推导,它通过循环另一个列表来形成一个列表。

    或者,可以使用map()。它更慢,但只是让你知道

    known_cards = list(map(lambda x : x, self.known_index))
    

    这会将列表中的每个值映射到一个函数,从而创建一个新元组。因此,我将map() 附在list() 中以提供列表

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-01
      • 2021-09-08
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      • 2018-07-09
      • 2020-12-27
      • 1970-01-01
      相关资源
      最近更新 更多