Python – 提取 key 的值(如果 key 同时出现在列表和字典中)
如果需要同时从列表和字典中提取键的值,可以使用一个简单的迭代和“all”运算符。
示例
以下对此进行了演示:
my_list = ["Python", "is", "fun", "to", "learn", "and", "teach", 'cool', 'object', 'oriented']
my_dictionary = {"Python" : 2, "fun" : 4, "learn" : 6}
K = "Python"
print("The value of K is ")
print(K)
print("The list is : " )
print(my_list)
print("The dictionary is : " )
print(my_dictionary)
my_result = None
if all(K in sub for sub in [my_dictionary, my_list]):
my_result = my_dictionary[K]
print("The result is : ")
print(my_result)输出
The value of K is
Python
The list is :
['Python', 'is', 'fun', 'to', 'learn', 'and', 'teach']
The dictionary is :
{'Python': 2, 'fun': 4, 'learn': 6}
The result is :
2说明
定义一个字符串列表并显示在控制台中。
定义一个值字典并显示在控制台中。
定义 K 的值并显示在控制台中。
值为 None。
使用“all”运算符和简单迭代来检查字典中的值是否出现在列表中。
如果为“是”,则该值将被赋予字典中的“K”元素。
此值将作为输出显示在控制台中。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP