Python 要将列表列表中的每个元素放入文件中吗
我正在制作一个高分列表,它的顺序应该由点数决定,点数是列表中列表的第二个元素。 这是我的代码:Python 要将列表列表中的每个元素放入文件中吗,python,python-3.x,Python,Python 3.x,我正在制作一个高分列表,它的顺序应该由点数决定,点数是列表中列表的第二个元素。 这是我的代码: 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.appe
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
但我希望它在文件中看起来像这样:
[
(
J
e
s
s
i
e
,
1
)
,
Jessie 1
John 2
我如何做到这一点?这是对(可选)键入声明的赞扬
您开始将其格式化为字符串有点太早了。最好将配对的结构保留更长一点:
for pair in sorted_by_second:
f.write(f'{pair}\n')
或者,如果您愿意,可以将其拆分为更灵活的:
您正在迭代一个字符串,因此迭代该字符串中的每个字符。只需省略字符串转换,并在循环中正确设置输出格式即可查找f字符串。您一方面使用键入,另一方面使用Python2.7样式的字符串格式,这两者不太适合:我在查找的副本中添加了一个使用dicts的简单答案。你发现我的Answare和其他人用pickle作为well@Patrick阿特纳:谢谢你,学到了一些新东西!我想出来了!谢谢,它工作得很好!我这里有一个后续问题:。如果你能帮助我,我真的很感激。