繁体   English   中英

2个要排序的字典的列表又回到2个列表(多个键值)

[英]2 Lists to Sorted Dictionary back to 2 Lists (Multiple Key Values)

我正在尝试获取两个列表:一个包含日期,一个包含乐谱,然后将它们压缩到字典中,然后按键值排序,然后将它们返回两个列表(仍在排序中)。 我遇到的问题是字典不保留多个键值。 我的代码如下:

date = ['2015/07/13', '2015/07/13', '2015/07/07', '2015/07/06',...] 
#there are 59 of these dates
Scores = [9.5, 13.9, 15.5, 12.9 .... ] #There are 59 of these scores
dictionary = dict(zip(date, Scores)) 
d = sorted(dictionary.items()) 
dte = []
scr = []
for i in d: 
    dte.append(i[0]) 
    scr.append(i[1])

但是,当我打印出这些列表时,长度仅为24,而不是应该的59。 多个相同的键不会退出。 我想知道是否有一种简单的方法可以将所有59个排序后的元素重新放入两个列表中。 我看了一些其他类似的python答案,但没有一个对我有用。 理想情况下,我不希望为日期创建对象(除非这是最简单的方法),但是当我尝试这样做时,我总是会出错。 另外,我使用的是Python 2.7。

date, Scores = zip(*sorted(zip(date, Scores)))

字典不支持相同键的多个副本。 您的密钥应该是唯一的。 实现此目的的一种方法是使键成为您的日期和分数的元组,除非您在同一天获得相同的分数。 在这种情况下,您可以添加第三个列表,编号为0到58,并在排序时将其用作第三个元素(使其成为三元组而不是元组)作为决胜局。

在这种情况下使用列表可能更有意义:

dates = ['2015/07/13', '2015/07/13', '2015/07/07', '2015/07/06'] 
scores = [9.5, 13.9, 15.5, 12.9] 

ldates_scores = zip(dates, scores)

dte = sorted(ldates_scores)
scr = sorted(ldates_scores, key=lambda x: x[1])

print dte
print scr
print

for date,score in dte:
    print "Date: %-10s   Score: %d" % (date, score)

print

for date,score in scr:
    print "Date: %-10s   Score: %d" % (date, score)

输出是两个列表,第一个列表按日期排序(因为您使用的是YYYY / MM / DD),第二个列表按分数排序。 我把两双放在一起。 输出如下:

[('2015/07/06', 12.9), ('2015/07/07', 15.5), ('2015/07/13', 9.5), ('2015/07/13', 13.9)]
[('2015/07/13', 9.5), ('2015/07/06', 12.9), ('2015/07/13', 13.9), ('2015/07/07', 15.5)]

Date: 2015/07/06   Score: 12
Date: 2015/07/07   Score: 15
Date: 2015/07/13   Score: 9
Date: 2015/07/13   Score: 13

Date: 2015/07/13   Score: 9
Date: 2015/07/06   Score: 12
Date: 2015/07/13   Score: 13
Date: 2015/07/07   Score: 15

字典中的键将是唯一的,因此您每个日期只捕获一个项目。 不需要dict ... zip将返回一个元组,然后将其排序。

 z = zip(date, Scores)
 sorted(z, key=lambda val: val[1], reverse=True)

暂无
暂无

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

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