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
我如何实现这一目标?
解决方案
对(可选)类型声明的赞誉!
您开始将其格式化为字符串有点太早了。最好将您的配对结构保留更长的时间:
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')
推荐阅读
- python - RNN 模型上的 CNN 权重
- swift - 如何以编程方式在 swift 5 (Xcode) 中获取呈现视图的大小
- dropbox - dropbox-api 隐藏显示名称
- r - pdftools 包无法解析字符
- python - 展平数据框
- python - choropleth() 在 folium 0.5.0 上得到了一个意想不到的关键字参数“bins”
- python - Alpha vantage AAPL 价格与其他数据源不一致
- java - 具有名为 Item 的类的 Arraylist
- html - 为什么定义给类的样式不能在元素?
- adobe - 如何在 adobe xd 中打开链接?