【问题标题】:Printing a dictionary without newlines?打印没有换行符的字典?
【发布时间】: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


【解决方案1】:

\n 是换行符。写入文件显示为换行符。您应该在打印之前将其删除:

print >> j, user[0].strip(), user[1].strip()

或者更好的是,一边看列表一边做:

z = [item.strip() for item in z.items()]

【讨论】:

  • 看起来我只需要字符串上的 .strip() 而不是浮点数。感谢您的回答!
猜你喜欢
  • 2020-07-26
  • 2013-12-23
  • 2015-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-02
  • 1970-01-01
相关资源
最近更新 更多