小编DCa*_*ugs的帖子

python字典中返回值的随机顺序

我不明白这一点,它会困扰我直到我明白。

此 python 代码计算每个字符出现在 'message' 变量中的次数:

message = 'Some random string of words'

dictionary= {}

for character in message.upper():
    dictionary.setdefault(character,0)
    dictionary[character] = dictionary[character] + 1

print(dictionary)
Run Code Online (Sandbox Code Playgroud)

如果您多次运行它,您会注意到计数每次都以看似随机的顺序返回。为什么是这样?我认为循环应该每次都从字符串的开头开始,并以一致的顺序返回值……但事实并非如此。是否有随机性的一些元素在setdefault(),print()或upper()方法,这也影响着字符串处理的顺序?

python

2
推荐指数
1
解决办法
1322
查看次数

标签 统计

python ×1