【发布时间】:2014-09-25 18:10:25
【问题描述】:
我创建了三个文本文件,每个文件都有 10 个用逗号分隔的随机数。然后我有一个 python 程序,它从用户那里接受一个文本文件的名称,将文本文件中的数字读入一个列表,然后对原始列表和排序后的列表进行排序和打印。
prompt = raw_input("Enter the name of the text file you want to open: ")
fileopen = open(prompt)
for line in fileopen:
numbers = line.split(",")
sortednumbers = sorted(numbers)
print numbers
print sortednumbers
但是,打印的结果列表始终只包含一个在数字末尾附加“\n”的值(例如 99\n)。我注意到它总是文本文件中的最后一个数字。我怎样才能让它只显示文本文件中没有“\n”的数字?
【问题讨论】:
-
你用什么语言编程?
-
算法列表和排序标签我不懂!
-
1) 始终使用
with打开文件,以便自动处理关闭文件。 2) 使用strip或rstrip,如numbers = line.strip().split(',')。见:stackoverflow.com/questions/275018/…
标签: python list sorting text formatting