写入文本文件时如何水平打印?
我正在尝试在文本文件中打印出这样的输出:
Bruce Wayne
5 5 0 0 100 15
Jessica Jones
12 0 6 6 10 6
Johnny Rose
6 2 0 4 20 10
Gina Linetti
7 4 0 3 300 15
Buster Bluth
3 0 2 1 50 1
但是在我的代码上,
def write_to_file(filename, player_list):
outfile = open(filename, "w")
for i in range(len(player_list)):
for j in player_list[i]:
outfile.write(str(j) + '\n')
outfile.close()
它是这样打印的:它像这样打印出来:
Bruce Wayne
5
5
0
0
100
15
Jessica Jones
12
0
6
6
10
6
Johnny Rose
6
2
0
4
20
10
Gina Linetti
7
4
0
3
300
15
Buster Bluth
3
0
2
1
50
1
player_list = [['Bruce Wayne', 5, 5, 0, 0, 100, 15], ['Jessica Jones', 12, 0, 6, 6, 10, 6], ['Johnny Rose', 6, 2, 0, 4, 20, 10], ['Gina Linetti', 7, 4, 0, 3, 300, 15], ['Buster Bluth', 3, 0, 2, 1, 50, 1]]
我不确定如何使底部排像上面的输出一样水平打印。我不允许使用任何列表功能,并且我必须使用循环,如我的代码所示。谢谢你!
I'm trying to print the output like this in a text file:
Bruce Wayne
5 5 0 0 100 15
Jessica Jones
12 0 6 6 10 6
Johnny Rose
6 2 0 4 20 10
Gina Linetti
7 4 0 3 300 15
Buster Bluth
3 0 2 1 50 1
But with my code here:
def write_to_file(filename, player_list):
outfile = open(filename, "w")
for i in range(len(player_list)):
for j in player_list[i]:
outfile.write(str(j) + '\n')
outfile.close()
It prints out like this:
Bruce Wayne
5
5
0
0
100
15
Jessica Jones
12
0
6
6
10
6
Johnny Rose
6
2
0
4
20
10
Gina Linetti
7
4
0
3
300
15
Buster Bluth
3
0
2
1
50
1
player_list = [['Bruce Wayne', 5, 5, 0, 0, 100, 15], ['Jessica Jones', 12, 0, 6, 6, 10, 6], ['Johnny Rose', 6, 2, 0, 4, 20, 10], ['Gina Linetti', 7, 4, 0, 3, 300, 15], ['Buster Bluth', 3, 0, 2, 1, 50, 1]]
and I'm not sure how to get the bottom row to print horizontally like the output I have above. I'm not allowed to use any list functions and I have to use a loop, as seen with my code. Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能将
player_list
的所有内容都相同,因为这些值意味着不同的内容。第一个值是播放器名称,其余的是分数之类的。因此,您的代码需要在第一个值之后放置一个新线,但仅在其余部分之间(在第二行末尾有一个newline)。尝试这样的事情:
无关,您可能需要与一起使用
来处理您的文件对象。即使有例外,它也会自动关闭文件:
You can't treat all the contents of your
player_list
the same, because the values mean different things. The first value is the player name, the rest are scores or something. So your code needs to put a newline after the first value, but only spaces between the rest (with a newline at the end of the second line).Try something like this:
Unrelatedly, you might want to use
with
to handle your file object. It will close the file automatically for you, even if there's an exception:喜欢这样做
do like so
您需要将播放器名称与值分开。
You need to separate the player name from the values.