Python - 提取值之和大于 K 的字典
当需要提取值之和大于 K 的字典时,可以使用一个简单的迭代和“if”条件。
示例
以下是对此进行演示 -
my_list = [{"Python" : 14, "is" : 18, "fun" : 19},{"Python" : 12, "is": 4, "fun" : 16},
{"Python" : 13, "is": 17, "fun" : 11},{"Python" : 13, "is": 16, "fun" : 13}]
print("The list :")
print(my_list)
K =35
print("The value for K :")
print(K)
my_result = []
for index in my_list:
sum = 0
for key in index:
sum += index[key]
if sum > K:
my_result.append(index)
print("The result is :")
print(my_result)输出
The list :
[{'Python': 14, 'is': 18, 'fun': 19}, {'Python': 12, 'is': 4, 'fun': 16}, {'Python': 13, 'is': 17, 'fun': 11}, {'Python': 13, 'is': 16, 'fun': 13}]
The value for K :
35
The result is :
[{'Python': 14, 'is': 18, 'fun': 19}, {'Python': 13, 'is': 17, 'fun': 11}, {'Python': 13, 'is': 16, 'fun': 13}]说明
定义了一个字典列表并将其显示在控制台上。
定义了 K 的值并将其显示在控制台上。
创建了一个空列表。
迭代该列表,并将求和值初始化为 0。
如果列表中存在特定的键,则将元素添加到求和中。
如果求和大于‘K’,则将索引值附加到空列表中。
此列表就是输出,显示在控制台上。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP