📌  相关文章
📜  Python|大于 K 的数字的索引

📅  最后修改于: 2022-05-13 01:54:25.080000             🧑  作者: Mango

Python|大于 K 的数字的索引

很多时候,我们可能会遇到需要查找索引而不是实际数字的问题,而且更多时候,结果是有条件的。想到的第一种方法可能是一个简单的索引函数并获得大于特定数字的索引,但是如果数字重复,这种方法会失败。让我们讨论一些可以成功解决这个问题的方法。

方法#1:使用循环
这个问题可以很容易地使用循环和蛮力方法来解决,在这种方法中,我们可以在迭代时检查索引,并在继续前进时将其附加到新列表中。

# Python3 code to demonstrate
# index of matching element using loop
  
# initializing list 
test_list = [12, 10, 18, 15, 8, 18]
  
# printing original list
print("The original list : " + str(test_list))
  
# using loop
# index of matching element
res = []
for idx in range(0, len(test_list)) :
    if test_list[idx] > 10:
        res.append(idx)
  
# print result
print("The list of indices greater than 10 : " + str(res))
输出 :
The original list : [12, 10, 18, 15, 8, 18]
The list of indices greater than 10 : [0, 2, 3, 5]

方法 #2:使用列表理解 + enumerate()
这两个函数的组合也可以有效地在一条线上执行此特定任务。 enumerate函数用于同时获取元素及其索引。

# Python3 code to demonstrate
# index of matching element
# using list comprehension + enumerate()
  
# initializing list 
test_list = [12, 10, 18, 15, 8, 18]
  
# printing original list
print("The original list : " + str(test_list))
  
# using list comprehension + enumerate()
# index of matching element
res = [idx for idx, val in enumerate(test_list) if val > 10]
  
# print result
print("The list of indices greater than 10 : " + str(res))
输出 :
The original list : [12, 10, 18, 15, 8, 18]
The list of indices greater than 10 : [0, 2, 3, 5]