这是我下面的代码,它主要输出我想要的内容,但它包含\ n在每个数字之后,我不知道如何摆脱它...任何帮助?谢谢!
def main():
scores = []
scores_file = open('scores.txt', 'r')
line_list = list(scores_file.readlines())
print(line_list)
i = 0
while i < len(line_list):
scores.append(line_list[i])
i += 1
main()
答案 0 :(得分:1)
with open('scores.txt', 'r') as f:
scores = [int(line.strip()) for line in f]
答案 1 :(得分:1)
with open('scores.txt') as f:
scores = f.read().splitlines()
答案 2 :(得分:0)
如果你想保持while循环(你不应该这样做)
def main():
scores = []
scores_file = open('scores.txt', 'r')
line_list = scores_file.readlines()
scores_file.close()
i = 0
while i < len(line_list):
scores.append(int(line_list[i].strip()))
i += 1
print(scores)
main()
如果您发现列表理解有点难以理解,可以将其分解为这样的实际循环。
def main():
scores = []
with open('scores.txt') as f:
for line in f:
scores.append(int(line.strip()))
print(scores)
你可以避免使用列表索引变量i
以及所有错误的可能性和可能性。