python - 在带有更多空格的文本文件中对数据进行排序会在 python 中产生错误
问题描述
我有对文本文件内容进行排序的片段。我的问题是得分后的值,因为我遇到了错误。
data = []
with open('data.txt') as f:
for line in f:
group, score, team = line.split(' ')
data.append((int(score), group.strip(), team.strip()))
data.sort(reverse=True)
print("Top Scores:")
for (score, group, team), _ in zip(data, range(3)):
print(f'{group} - {score} - {team}')
datafile.txt(3 列 GROUP、SCORE、TEAM NAME)
asdsd 1 dream team
swsds 3 never mind us
2sdsg 1 diehard
sklks 2 just cool
asedd 5 dont do it
错误:#-- 如果最后一列没有空格,则可以正常工作。
ValueError: too many values to unpack (expected 3).
解决方案
用正则表达式分割行:
import re
...
for line in j:
group, score, team = re.split(r' (-?\d*\.?\d+) ', line.strip('\n').strip())
data.append((int(score), group.strip(), team.strip()))
print(data)
给出:
[(1, 'asdsd', 'dream team'), (3, 'swsds', 'never mind us'), (1, '2sdsg', 'diehard'), (2, 'sklks', 'just cool')]
推荐阅读
- java - FCM:使用 Java 服务器设置 TTL(“time_to_live”或寿命)属性(Google 文档错误/不清楚)
- hyperledger-fabric - 如何扩展结构网络以在数千个用户/对等/组织之间共享私有数据?
- rest - 如何将来自一个 HttpRequest 的 Json 请求正文作为下一个 http 请求中的值传递?
- python - Python 数学在命令行中是正确的,而在 py 文件中却是错误的?
- php - php 和 Microsoft Graph API 中的带时区的 DateTime
- surf - 使用YOLO对物体进行分类,然后使用SURF
- r - 穿针引线:找到对应于外部函数形式的实际参数的名称
- r - 如何正确绘制月度销售数据?
- c# - 从接口集合中移除一个元素
- django - 在 Django 中使用日历搜索和显示结果