简体   繁体   English

在Python中对列表进行排序

[英]Sorting dictionary of lists in Python

I'm making an auction program and need to sort stored bids by price, and date. 我正在制定拍卖程序,需要按价格和日期对存储的出价进行排序。 I'm trying to pull any bids that equal the reserve price, and find the earliest one. 我试图拉任何等于底价的出价,并找到最早的出价。 I've pulled the line below from another question, however I need to find the max bid (sorted in reverse to bring highest bid and then oldest bid if there are two of the same value). 我已经从另一个问题中拉出了下面的行,但是我需要找到最高出价(如果有两个相同的值,则反向排列以带来最高出价,然后是最早的出价)。

sorted(stored_bids_1.items(), key=lambda e:e[1][2][3][4])

The dictionary has the following info: 该词典具有以下信息:

stored_bids_1 {bid_number : [cust_bid_price, bid_date_time, cust_num_seats, cust_name]}

I'd like the bids to be ranked by bid price, then date&time. 我希望按出价,然后按日期和时间对出价进行排名。

Any help is much appreciated! 任何帮助深表感谢!

At first glance big thing that I can think of doing is to use a different datastructure. 乍一看,我能想到的一件大事就是使用不同的数据结构。 The dicitonary you have works well for storing it the information, but is clearly creating a hurtle. 您拥有的二分法可以很好地存储信息,但显然会带来麻烦。 I'd suggest another a dictionary of dictionaries maybe, that way you could access the different values (cust_bid_price, bid_date_time, etc.) by the keys they are in the sub-dictionaries. 我建议使用另一本字典词典,这样您可以通过子词典中的键访问不同的值(cust_bid_price,bid_date_time等)。 It's definitely not perfect, but it may lead to another way of looking at this and solving the problems you have. 它绝对不是完美的,但是它可能会导致另一种看待这个问题并解决您所遇到的问题的方式。

I need to find the max bid (sorted in reverse to bring highest bid and then oldest bid if there are two of the same value). 我需要找到最高出价(如果有两个相同的值,则反向排列以带来最高出价,然后是最早的出价)。

This can be done by taking advantage of sort stability and doing two successive sorts: 这可以通过利用排序稳定性并进行两个连续的排序来完成:

bids.sort(key = lambda e: e[1])               # where e[1] is bid_date_time
bids.sort(key = lambda e: e[0], reverse=True) # where e[0] is cust_bid_price

See the Python Sorting HowTo guide for more explanation and another example . 有关更多说明和另一个示例,请参见Python Sorting HowTo指南。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM