要将列表列表中的每个元素放到fi中吗

2024-04-19 04:12:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做一个高分列表,它的顺序应该由点数决定,点数是列表中的第二个元素。 这是我的密码:

from typing import List, Tuple

name1 = 'John'
name2 = 'Ron'
name3 = 'Jessie'
points1 = 2
points2 = 3
points3 = 1

highscore: List[Tuple[str, int]] = []
highscore.append((name1, points1))
highscore.append((name2, points2))
highscore.append((name3, points3))

print(highscore)

sorted_by_second = sorted(highscore, key=lambda X: X[1])

highscore_list= str(sorted_by_second)

将列表导出到文件

with open('highscore.txt', 'w') as f:
for item in highscore_list:
    f.write("%s\n" % item)

在文件中是这样的:

 [
 (
 J
 e
 s
 s
 i
 e
 ,

 1
 )
 ,

但我想让它在文件里看起来像这样:

  Jessie 1
  John   2

我如何做到这一点


Tags: 文件列表johnlistsorted点数appendtuple
1条回答
网友
1楼 · 发布于 2024-04-19 04:12:52

对(可选)输入声明的赞誉

你把它格式化为字符串有点太早了。最好把你的成对的结构保留得再长一点:

for pair in sorted_by_second:
    f.write(f'{pair}\n')

或者,如果您愿意的话,可以将它们分开,以获得更灵活的formatting

for name, points in sorted_by_second:
    f.write(f'{name} scored {points}.\n')

相关问题 更多 >