【问题标题】:Finding index of smallest element in list only for elements at a certain index仅针对某个索引处的元素查找列表中最小元素的索引
【发布时间】:2019-04-24 17:44:01
【问题描述】:

假设我有以下列表:

possible_moves = [0, 1, 2, 3]
q_array = [4, 2, 3, 7, -10]

我想只为possible_moves 中索引处的元素获取q_array 中最小元素的索引。因此,这两个列表的输出应该是 1。

我使用以下代码实现了它,但它确实不是很 Pythonic。

best_value = q_array[random.choice(possible_moves)]
for move in possible_moves:
    if q_array[move] <= best_value:
        best_value = q_array[move]
        move_chosen = move
return move_chosen

编辑:返回的值应该是最小值的索引,而不是值本身。在上面的示例中,返回 1 是因为它是索引在 possible_moves 的元素中的最小值的索引

【问题讨论】:

    标签: python


    【解决方案1】:

    构建一个仅包含所需元素的列表推导式,然后找到该列表的 min()

    min([q_array[x] for x in possible_moves])
    

    【讨论】:

    • 谢谢!返回的值应该是那个最小元素的索引,而不是值。
    • 这是值 --> q_array[x]。我实际上逐字给出了相同的答案,但我被秒了;P
    • @Johny 你的问题是我想得到最小的元素,而不是最小元素的索引
    • @JohnGordon 已编辑!
    【解决方案2】:

    将数据放入一个dict,然后得到最小值的key。

    >>> d = {i: q_array[i] for i in possible_moves}
    >>> move_chosen = min(d, key=d.get)
    1
    

    这类似于blhsing's answer

    【讨论】:

      【解决方案3】:

      您可以使用possible_moves列表上的min函数,以q_array列表的__getitem__方法为关键函数:

      min(possible_moves, key=q_array.__getitem__)
      

      返回:1

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-02
        • 2019-01-12
        • 2020-12-05
        • 2018-10-17
        • 2017-09-23
        • 1970-01-01
        相关资源
        最近更新 更多