首页 > 解决方案 > 想要将列表列表中的每个元素放入文件中

问题描述

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

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

我如何实现这一目标?

标签: pythonpython-3.x

解决方案


对(可选)类型声明的赞誉!

您开始将其格式化为字符串有点太早了。最好将您的配对结构保留更长的时间:

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

或者,如果您愿意,可以将它们拆分为更灵活的格式

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

推荐阅读