我在做一个高分列表,它的顺序应该由点数决定,点数是列表中的第二个元素。 这是我的密码:
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
我如何做到这一点
对(可选)输入声明的赞誉
你把它格式化为字符串有点太早了。最好把你的成对的结构保留得再长一点:
或者,如果您愿意的话,可以将它们分开,以获得更灵活的formatting:
相关问题 更多 >
编程相关推荐