比 K 大的数字索引


在本教程中,我们将找到大于给定数字 K 的数字的索引。让我们看看不同的方法来找到它们。

解决此问题最常见的方法是使用循环。让我们看看解决此问题所需的步骤。

  • 初始化列表和 K。
  • 使用其长度遍历列表。
  • 如果您发现任何大于 K 的数字,则打印当前索引。

示例

 动态演示

# initializing the list and K
numbers = [3, 4, 5, 23, 12, 10, 16]
K = 10
# iterating over thAe list
for i in range(len(numbers)):
   # checking the number greater than K
   if numbers[i] > K:
      # printing the number index
      print(i, end=' ')

输出

如果您运行上述代码,您将获得以下结果。

3 4 6

让我们使用enumerate函数解决问题。它为您提供每个迭代的元组,其中包括元素的索引和元素。

示例

 动态演示

# initializing the list and K
numbers = [3, 4, 5, 23, 12, 10, 16]
K = 10
# finding indexes of the numbers greater than K
result = [index for (index, number) in enumerate(numbers) if number > K]
# printing the indices
print(*result)

输出

如果您运行上述代码,您将获得以下结果。

3 4 6

结论

如果您对教程有任何疑问,请在评论区中提到。

更新于: 07-Jul-2020

479 次浏览

开启你的职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.