【问题标题】:Finding list indexes of numbers greater than a value [duplicate]查找大于值的数字的列表索引[重复]
【发布时间】:2021-01-09 15:37:12
【问题描述】:

如果我们有一些条件,如何在 python 列表中获取数字的索引:

    test_list=[1,5,7,11,20,26,89]
    # find index of number>13

答案:4(索引值)

【问题讨论】:

  • 问之前记得搜索一下吗? this帖子中有很多合适的解决方案。

标签: python python-3.x list


【解决方案1】:

你也可以通过以下方式使用numpy:

import numpy as np
x = np.array([1,5,7,11,20,26,89])
x[np.where(x>13)][0]  # 20

请注意,您要求索引但您希望该值,所以如果您希望索引:

np.where(x>13)[0]  # array([4, 5, 6])

会给你所有符合条件的指标

【讨论】:

  • 对不起,我要索引
  • @yashcode17 所以只需使用np.where(x>13) 就能满足您的需求
【解决方案2】:

您可以简单地遍历列表并在条件为真时中断:

test_list = [1,5,7,11,20,26,89]
for i, value in enumerate(test_list):
    if value > 13:
        break

print(value)  # 20
print(i)      # 4

【讨论】:

    【解决方案3】:

    您可以使用内置索引方法。例如:

    test_list = [1,5,7,11,20,26,89]
    test_list.index(5)
    

    将返回 1。 因此,您可以通过以下方式使用它来获得所需的结果:

    for i in test_list:
        if i > 13:
            print(test_list.index(i))
    

    编辑:增加了如何使用索引方法来满足问题的要求

    【讨论】:

    • index() 没有条件,所以除非他知道价值,否则它不会真正帮助他
    • @DavidS 我更新了我的答案,包括在检查条件时使用索引方法的多种方法之一。
    猜你喜欢
    • 1970-01-01
    • 2018-10-24
    • 2012-06-29
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多