Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 定购信息(柜台)是否总是提供定购的措辞?_Python_Python 3.x_Counter_Ordereddictionary - Fatal编程技术网

Python 定购信息(柜台)是否总是提供定购的措辞?

Python 定购信息(柜台)是否总是提供定购的措辞?,python,python-3.x,counter,ordereddictionary,Python,Python 3.x,Counter,Ordereddictionary,我有如下代码,我想得到插入键的顺序 from collections import Counter, OrderedDict s = 'abcdabcd' d = OrderedDict(Counter(s)) print(d) 输出:OrderedDict([('a',2),('b',2),('c',2),('d',2)]) 这样做是否正确,每次运行代码是否都能获得相同的顺序?是的,如果您重复运行代码,只要您使用Python 3.6或更新版本,它将产生相同的顺序 这是因为迭代Counter(

我有如下代码,我想得到插入键的顺序

from collections import Counter, OrderedDict
s = 'abcdabcd'
d = OrderedDict(Counter(s))
print(d)
输出:
OrderedDict([('a',2),('b',2),('c',2),('d',2)])


这样做是否正确,每次运行代码是否都能获得相同的顺序?

是的,如果您重复运行代码,只要您使用Python 3.6或更新版本,它将产生相同的顺序

这是因为迭代
Counter()
对象将始终按插入顺序为您提供项目,并且该顺序由输入决定。如果
s
输入没有改变,那么
OrderedDict(计数器)的输出也不会改变

请注意,这是键的插入顺序,而不是计数器产生的顺序。most_common()
;从
计数器()
传递到
OrderedDict
时,项目未排序。顺序保持稳定,因为在Python3.6中,字典的Python实现被更改为使用更少的内存,这反过来又产生了记录插入顺序的副作用。从Python3.7开始,在字典中维护插入顺序成为语言规范的一部分。看

因此,键按第一次出现的顺序列出:

>>> from collections import Counter, OrderedDict
>>> OrderedDict(Counter("aaabbc"))
OrderedDict([('a', 3), ('b', 2), ('c', 1)])
>>> OrderedDict(Counter("abbccc"))
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
>>> OrderedDict(Counter("cba"))
OrderedDict([('c', 1), ('b', 1), ('a', 1)])
如果要捕获不同的排序,则需要在将项目传递到
orderedict()
对象之前对其进行排序。例如,对于最常见的排序(首先是最高计数),传入
计数器的结果。most_common()

如果人们想知道为什么您仍然可以使用
orderedict
:使用这种类型,您可以重新订购密钥(通过
orderedict.move_to_end()
)。您还可以对有序的dict(及其字典视图)使用
reversed()

(注:我在初稿时弄错了,在核实后我调整了这个答案)

>>> s = "abbcaaacbbbbc"
>>> OrderedDict(Counter(s).most_common())
OrderedDict([('b', 6), ('a', 4), ('c', 3)])