【发布时间】: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
如果我们有一些条件,如何在 python 列表中获取数字的索引:
test_list=[1,5,7,11,20,26,89]
# find index of number>13
答案:4(索引值)
【问题讨论】:
标签: python python-3.x list
你也可以通过以下方式使用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])
会给你所有符合条件的指标
【讨论】:
np.where(x>13) 就能满足您的需求
您可以简单地遍历列表并在条件为真时中断:
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
【讨论】:
您可以使用内置索引方法。例如:
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() 没有条件,所以除非他知道价值,否则它不会真正帮助他