比 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.