我有以下代码:
test=open("NewTextDocument.txt", "r")
lines1 = (test.readlines())
lines1.sort()
print(lines1)`
我用它来存储一个包含以下内容的文本文件:
('lars', ' in class', '1', ' has got a score of', 8)
('lars2', ' in class', '1', ' has got a score of', 1)
('as', ' in class', '1', ' has got a score of', 1)
('12', ' in class', '1', ' has got a score of', 0)
('lars', ' in class', '1', ' has got a score of', 8)
('lars', ' in class', '1', ' has got a score of', 8)
('lars', ' in class', '1', ' has got a score of', 7, ' with a time of', 39.79597997665405)
('test', ' in class', '1', ' has got a score of', 1, ' with a time of', 17)
我要做的是按字母顺序对文件中的行进行排序,同时保留换行符。例如:
('as', ' in class', '1', ' has got a score of', 1)
('lars', ' in class', '1', ' has got a score of', 8)
('lars2', ' in class', '1', ' has got a score of', 1)
但是,运行代码后得到的结果是:
["('12', ' in class', '1', ' has got a score of', 0)\n",
"('as', ' in class', '1', ' has got a score of', 1)\n",
"('lars', ' in class', '1', ' has got a score of', 7, ' with a time of', 39.79597997665405)\n",
"('lars', ' in class', '1', ' has got a score of', 8)\n",
"('lars', ' in class', '1', ' has got a score of', 8)\n",
"('lars', ' in class', '1', ' has got a score of', 8)\n",
"('lars2', ' in class', '1', ' has got a score of', 1)\n",
"('test', ' in class', '1', ' has got a score of', 1, ' with a time of', 17)"]
我怎样才能解决这个问题?你知道吗
你所犯的错误就是打印一个没有任何格式的列表。打印行1只会弹出一个包含该列表所有内容的长行。您要循环浏览列表并一次打印一行:
我添加了逗号,因为您的所有行都以换行符结尾,所以用逗号结尾打印意味着它不会每次都添加额外的换行符。你知道吗
再加上
完整的代码将变成
输出
相关问题 更多 >
编程相关推荐