python - 在 Python 中对项目进行排序
问题描述
输入:
`videoshop=[]
for i in range(0,3,1):
movie={}
print("Enter Movie Name")
movie["Name"]=raw_input("Enter Here: ")
print("Enter Movie Duration")
movie["Duration"]=raw_input("Enter Here: ")
print("Enter Movie Age")
movie["Age"]=raw_input("Enter Here: ")
print("Enter Movie Price")
movie["Price"]=raw_input("Enter Here: ")
videoshop.append(movie)
print(videoshop)`
输出
`[{'Duration': '51', 'Age': '16+', 'Name': 'Jeff', 'Price': '$99'}, {'Duration':
'52', 'Age': '14', 'Name': 'Darm', 'Price': '$99'}, {'Duration': '56', 'Age': '18+',
'Name': 'Shaw', 'Price': '$102'}]`
问题
我需要输出来显示 [{'name':'jeff','Duration':'51', 'Age':'16+','Price':'$99'}]
我已经尝试对对象进行排序,但是这段代码失败了......
解决方案
pythonsorted
函数对于排序项目非常强大。
下面的示例将按价格对列表中的项目进行排序。key
传递给的属性sorted
告诉它应该按什么值排序。在这种情况下,我从价格的开头去掉 $,将其转换为整数并按此排序。
videoshop = [{'Duration': '51', 'Age': '16+', 'Name': 'Jeff', 'Price': '$99'}, {'Duration':
'52', 'Age': '14', 'Name': 'Darm', 'Price': '$99'}, {'Duration': '56', 'Age': '18+',
'Name': 'Shaw', 'Price': '$102'}]
by_price = sorted(videoshop, key=lambda x: int(x['Price'].replace('$','')))
按持续时间排序,思路是一样的,只是我们只是将持续时间转换为整数。
by_duration = sorted(videoshop, key=lambda x: int(x['Duration']))
如果要对字典中出现的字段进行排序,则需要使用有序字典,因为普通字典键是无序的。下面的代码片段显示了如何使用所需的键创建有序字典。
from collections import OrderedDict
for i in range(0,3,1):
movie = OrderedDict.fromkeys(['Name','Duration','Age','Price'])
推荐阅读
- xamarin.forms - Xamarin Forms:将号码添加到电话簿后如何获取电话的最新联系人?
- javascript - 节点应用程序未使用 npm start 在正确的端口中运行。显示随机端口
- data-structures - AVL 树的插入和删除
- excel - 如何将变量设置为跨工作表的相同单元格范围并放置相同的值?
- knockout.js - 如何在淘汰赛中绑定视图模型的集合
- ruby - combine_pdf gem:PDF 已加密!尝试解密 - 尚未完全支持
- wireshark - 使用大小过滤数据包 Wireshark
- angular - Angular 12 - 检查其是否登录启动 - 初始化程序工作错误
- react-native - @react-native-community/datetimepicker 安装抛出错误
- python - 在 python 中:如何使用括号中的列值和另一个值创建新列。新列= column1(column2)