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 值的索引。
将其分配给一个变量。
根据这个变量是“真”还是“假”,在控制台上显示相关信息。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP