如何在python中对字典列表进行排序(使用浮点值字段)?

如何在python中对字典列表进行排序(使用浮点值字段)?,python,sorting,floating-point,Python,Sorting,Floating Point,我在Python的字典列表中有这组值 [ {'dep_price': '42.350', 'dep_date': '8-Mar-2017', 'trip_type': 'dep'}, {'dep_price': '42.350', 'dep_date': '9-Mar-2017', 'trip_type': 'dep'}, {'dep_price': '36.350', 'dep_date': '10-Mar-2017', 'trip_type': 'dep'} ] 如何根据字段“dep_

我在Python的字典列表中有这组值

[
{'dep_price': '42.350', 'dep_date': '8-Mar-2017', 'trip_type': 'dep'}, 
{'dep_price': '42.350', 'dep_date': '9-Mar-2017', 'trip_type': 'dep'}, 
{'dep_price': '36.350', 'dep_date': '10-Mar-2017', 'trip_type': 'dep'}
]
如何根据字段“dep_price”作为浮点值对它们进行排序?

您可以使用带有键函数的
sorted()

代码:

a_list = [
    {'dep_price': '42.350', 'dep_date': '8-Mar-2017', 'trip_type': 'dep'},
    {'dep_price': '42.350', 'dep_date': '9-Mar-2017', 'trip_type': 'dep'},
    {'dep_price': '36.350', 'dep_date': '10-Mar-2017', 'trip_type': 'dep'}
]

a_new_list = sorted(a_list, key=lambda price: float(price['dep_price']))
print('\n'.join(['%s' % x for x in a_new_list]))
{'trip_type': 'dep', 'dep_price': '36.350', 'dep_date': '10-Mar-2017'}
{'trip_type': 'dep', 'dep_price': '42.350', 'dep_date': '8-Mar-2017'}
{'trip_type': 'dep', 'dep_price': '42.350', 'dep_date': '9-Mar-2017'}
结果:

a_list = [
    {'dep_price': '42.350', 'dep_date': '8-Mar-2017', 'trip_type': 'dep'},
    {'dep_price': '42.350', 'dep_date': '9-Mar-2017', 'trip_type': 'dep'},
    {'dep_price': '36.350', 'dep_date': '10-Mar-2017', 'trip_type': 'dep'}
]

a_new_list = sorted(a_list, key=lambda price: float(price['dep_price']))
print('\n'.join(['%s' % x for x in a_new_list]))
{'trip_type': 'dep', 'dep_price': '36.350', 'dep_date': '10-Mar-2017'}
{'trip_type': 'dep', 'dep_price': '42.350', 'dep_date': '8-Mar-2017'}
{'trip_type': 'dep', 'dep_price': '42.350', 'dep_date': '9-Mar-2017'}

它可能重复,看起来你想让我们为你写一些代码。虽然许多用户愿意为陷入困境的程序员编写代码,但他们通常只在海报已经试图自己解决问题时才提供帮助。演示这项工作的一个好方法是包括您迄今为止编写的代码、示例输入(如果有)、预期输出和实际获得的输出(输出、回溯等)。你提供的细节越多,你可能得到的答案就越多。检查和。@TigerhawkT3对不起,您弄错了。。。下面是我尝试过的一段代码……排序(list,key=itemgetter(field\u name),reverse=True)。。。字段名传递为“dep\u price”的位置我怎么会错呢?我没有看到任何代码,也没有试图自己解决这个问题,甚至没有你的任何初步想法。。。只是一个任务和一个解决方案请求。尝试添加
'dep_price'
为的内容,例如
'100.205'
@Stephen Rauch。。。谢谢我花了一些时间来尝试理解您的解决方案中的“lambda”,以及您在列表上进行迭代的方式。现在分类了。谢谢你的帮助