比 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
結論
如果您對教程有任何疑問,請在評論區中提到。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP