用 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 是否存在於列表中。
  • 如果存在,則結果顯示在控制檯上。

更新時間:2021 年 9 月 16 日

444 人檢視

開啟您的職業生涯

完成課程取得認證

開始
廣告
© . All rights reserved.