为什么我的python dict变得无序?
发布时间:2020-12-20 11:33:26 所属栏目:Python 来源:网络整理
导读:参见英文答案 Why is python ordering my dictionary like so? ????????????????????????????????????3个 ???????????? Dictionaries: How to keep keys/values in same order as declared?????????????????????????????????????12个 我用这个来制作一个多年
参见英文答案 >
Why is python ordering my dictionary like so? ????????????????????????????????????3个
>???????????? Dictionaries: How to keep keys/values in same order as declared?????????????????????????????????????12个 我用这个来制作一个多年来以某个字母开头的名字百分比图.当绘制(和打印)我的词典(letter_d)时,键是无序的,而不是像它们被添加到词典中一样顺序.有没有办法解决这个问题,我相信我会按顺序将它们添加到dict中.如果没有,我可以创建一个方法连接我的散点图的点,以模拟正确的线图? import csv import matplotlib.pyplot as plt start = 1880 stop = 1890 x = [] years = range(start,stop +1) print years letter_d = {} year_d = {} alphabet = ['Z']#,'C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] for i in alphabet: letter_d[i] = 0 for year in years: filename = 'yob' + str(year) + '.txt' z = open(filename) year_d[int(year)] = 0 letter_d[i] = year_d c = 0 d = 0 for line in z: y = line.strip().split(',') y.remove(y[1]) c += int(y[1]) if i in y[0]: d += int(y[1]) year_d[year] = float(d)/float(c) #x.append(y) #print year_d print year_d.keys() plt.plot(year_d.keys(),year_d.values()) plt.show() 解决方法
Python词典总是无序的.
在您的情况下,您根本不需要字典.使用两个列表;一个是您已经从范围生成的年份列表,另一个是计算值: year_values = [] for year in years: # ... year_values.append(float(d)/float(c)) plt.plot(years,year_values) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容