首页 > 解决方案 > 在 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'}] 我已经尝试对对象进行排序,但是这段代码失败了......

标签: pythonencodingpython-requests

解决方案


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'])

推荐阅读