gpt4 book ai didi

python - 按键值的顺序绘制 python dict

转载 作者:IT老高 更新时间:2023-10-28 22:20:18 24 4
gpt4 key购买 nike

我有一个看起来像这样的python字典:

In[1]: dict_concentration
Out[2] : {0: 0.19849878712984576,
5000: 0.093917341754771386,
10000: 0.075060643507712022,
20000: 0.06673074282575861,
30000: 0.057119318961966224,
50000: 0.046134834546203485,
100000: 0.032495766396631424,
200000: 0.018536317451599615,
500000: 0.0059499290585381479}

它们的键是 int 类型,值是 float64 类型。不幸的是,当我尝试用线条绘制它时,matplotlib 连接了错误的点(附图)。我怎样才能让它按照键值的顺序连接线? enter image description here

最佳答案

Python 字典是无序的。如果你想要一个有序的字典,使用 collections.OrderedDict

在你的情况下,在绘图之前按键对字典进行排序,

import matplotlib.pylab as plt

lists = sorted(d.items()) # sorted by key, return a list of tuples

x, y = zip(*lists) # unpack a list of pairs into two tuples

plt.plot(x, y)
plt.show()

这是结果。 enter image description here

关于python - 按键值的顺序绘制 python dict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37266341/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com