Python——檢查特定值是否與 K 鍵相對應


當需要檢查特定值是否與鍵“K”相對應時,需要使用列表解析。

以下是其演示:

示例

 線上演示

my_list = [{"python" : "14", "is" : "great", "fun" : "1`"},{"python" : "cool", "is" : "fun", "best" : "81"},{"python" : "93", "is" : "CS", "amazing" : "16"}]

print("The list is :")
print(my_list)

K = "python"
print("The value of K is ")
print(K)

value = "cool"

my_result = value in [index[K] for index in my_list]

print("The result is :")

if(my_result == True):
   print("The value is present in with respect to key ")
else:
   print("The value isn't present with respect to key")

輸出

The list is :
[{'python': '14', 'is': 'great', 'fun': '1`'}, {'python': 'cool', 'is': 'fun', 'best': '81'}, {'python': '93', 'is': 'CS', 'amazing': '16'}]
The value of K is
python
The result is :
The value is present in with respect to key

說明

  • 定義了一個字典元素列表並將其顯示在控制檯上。

  • 定義一個 K 值並將其顯示在控制檯上。

  • 定義另一個字串。

  • 使用列表解析對列表進行迭代,並在字典列表中搜索 K 值的索引。

  • 將其分配給一個變數。

  • 根據這個變數是“真”還是“假”,在控制檯上顯示相關資訊。

更新時間: 2021 年 9 月 6 日

120 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始學習
廣告