【发布时间】:2015-04-29 00:02:36
【问题描述】:
我正在尝试在我的打印输出上正确设置格式,但它比应有的复杂。我的目标是让我的代码在字典中读取,将其转换为列表,对其进行排序,然后将其打印回一个看起来像的文本文件
“字符串”“浮点数”
“字符串”“浮点数”
“字符串”“浮点数”
当它打印时
字符串
浮动
字符串
浮动
查看作为我的字典的原始数据,它看起来像:
{'blahblah\n': 0.3033367037411527, 'barfbarf\n': 0.9703779366700716,
我怀疑 \n 换行命令与此有关。但我似乎无法减轻它。我的代码如下:
#Open the text file and read it back it
h = open('File1.txt', 'r')
my_dict = eval(h.read())
#Print out the dictionary
print "Now tidying up the data......"
z = my_dict
#Turn the dictionary into a list and print it
j = open('File2.txt', 'w')
z = z.items()
z.sort(key=lambda t:t[1])
z.reverse()
for user in z:
print >> j, user[0], user[1]
j.close()
这段代码在我程序的几乎所有其他部分都能完美运行。出于某种原因,它在这里遇到了问题。
【问题讨论】:
-
试试
strip()。 -
\n肯定与它有关!
标签: python dictionary file-io printing formatting