最佳答案
我在使用 collections.OrderedDict
类时遇到了一些麻烦。我在 Raspbian 上使用 Python 2.7,这是 Raspberry Pi 的 Debian 发行版。我正在尝试打印两本字典,以便进行比较(并排)进行文本冒险。顺序对于准确比较是必不可少的。
无论我怎样尝试,字典还是以它们通常无序的方式印刷。
这就是我在 RPi 上做的结果:
import collections
ship = {"NAME": "Albatross",
"HP":50,
"BLASTERS":13,
"THRUSTERS":18,
"PRICE":250}
ship = collections.OrderedDict(ship)
print ship
# OrderedDict([('PRICE', 250), ('HP', 50), ('NAME', 'Albatross'), ('BLASTERS', 13), ('THRUSTERS', 18)])
显然有些地方不对劲,因为它正在打印函数调用,并将键和值组放入一个嵌套列表中..。
这是我在电脑上运行类似程序得到的结果:
import collections
Joe = {"Age": 28, "Race": "Latino", "Job": "Nurse"}
Bob = {"Age": 25, "Race": "White", "Job": "Mechanic", "Random": "stuff"}
#Just for clarity:
Joe = collections.OrderedDict(Joe)
Bob = collections.OrderedDict(Bob)
print Joe
# OrderedDict([('Age', 28), ('Race', 'Latino'), ('Job', 'Nurse')])
print Bob
# OrderedDict([('Age', 25), ('Race', 'White'), ('Job', 'Mechanic'), ('Random', 'stuff')])
这一次,它是有序的,但它不应该打印其他的东西,虽然是吗?(将其放入列表并显示函数调用。)
我错在哪里?它不应该与 Python 的 π 版本有任何关系,因为它只是 Linux 版本。