用 Python 程式在列表中查詢字串
當需要在列表中查詢字串時,可以使用簡單的“if”條件以及“in”運算子。
示例
以下是此演示:
my_list = [4, 3.0, 'python', 'is', 'fun']
print("The list is :")
print(my_list)
key = 'fun'
print("The key is :")
print(key)
print("The result is :")
if key in my_list:
print("The key is present in the list")
else:
print("The key is not present in the list")輸出
The list is : [4, 3.0, 'python', 'is', 'fun'] The key is : fun The result is : The key is present in the list
說明
- 定義了一個由整數和字串組成的列表,並顯示在控制檯上。
- 定義了 key 的值,並顯示在控制檯上。
- 使用了'if'迴圈來檢查 key 是否存在於列表中。
- 如果存在,則結果顯示在控制檯上。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP