Python – 根据顺序值筛选字典
当需要使用顺序值来筛选时,使用“sorted”方法和列表解析。
示例
以下对其进行演示例子
my_list = [{'python': 2, 'is': 8, 'fun': 10},
{'python': 1, 'for': 10, 'coding': 9},
{'cool': 3, 'python': 4}]
print("The list is :")
print(my_list)
my_result = [index for index in my_list if sorted(
list(index.values())) == list(index.values())]
print("The resultant dictionary is :")
print(my_result)输出
The list is :
[{'python': 2, 'fun': 10, 'is': 8}, {'python': 1, 'coding': 9, 'for': 10}, {'python': 4, 'cool': 3}]
The resultant dictionary is :
[{'python': 1, 'coding': 9, 'for': 10}]说明
定义了字典元素的列表,并将其显示在控制台中。
使用列表解析来迭代列表元素,并使用“sorted”方法通过访问字典值并检查它是否等于下一个元素的值来对列表进行排序。
将其分配给一个变量。
该变量在控制台中显示为输出。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP