简体   繁体   English

Python中的输出顺序错误

[英]Wrong output order in Python

There is something wrong with my code. 我的代码有问题。 It does not print out the way I wanted it to be. 它没有打印出我想要的方式。

print("Hello Herp, welcome to Derp v1.0 :)")

inFile = input("Herp, enter symbol table file: ")
symTbl = {}
for line in open(inFile):
    i = line.split()
    symTbl[i[0]] = int(i[1])
print("Derping the symbol table (variable name => integer value)...")
for var1 in symTbl:
    print(var1 + " => " + str(symTbl[var1]))

When I open the textfile, it prints out this: 当我打开文本文件时,它打印出来:

z => 30
y => 20
x => 10

Which is not right, I am expecting to have output like this: 哪个不对,我希望有这样的输出:

x => 10
y => 20
z => 30

The original textfile is this: 原始文本文件是这样的:

x 10
y 20
z 30

You need to use an Ordered Dictionary. 您需要使用有序词典。 There is no guarantee in what order you will get your keys when you read them(using the for loop in your case) from a dictionary. 当您从字典中读取密钥(在您的情况下使用for循环)时,无法保证您将获得密钥的顺序。 The OrderedDict will always return the keys in the order they were entered. OrderedDict将始终按照输入的顺序返回键。

from collections import OrderedDict
symTbl = OrderedDict()

An OrderedDict preserves the order of insertion, it does not sort by key. OrderedDict保留插入顺序,不按键排序。 Sometimes that's what people want, sometimes it's not. 有时这就是人们想要的东西,有时却不是。

If you're only needing sorted keys once, you could do something like: 如果您只需要一次排序键,您可以执行以下操作:

for key, value in sorted(list(symTbl.items())):
    print('{} ==> {}'.format(key, value))

If you need sorted values many times (IOW, inside a loop), you're better off with a treap, red-black tree or (on disk, in case your values don't fit in memory) BTree. 如果您需要多次排序值(IOW,在循环内),最好使用treap,红黑树或(在磁盘上,以防您的值不适合内存)BTree。 EG: http://en.wikipedia.org/wiki/Treap EG: http//en.wikipedia.org/wiki/Treap

Or, you can just sort the dictionary: 或者,您可以对字典进行排序:

for var1 in sorted(symTbl):
    print(var1 + " => " + str(symTbl[var1]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM