本文目录导读:

要查看一场比赛的“进球总数”,关键在于你手头的数据是什么格式,Python 处理这类问题非常灵活。
下面我为你提供 3 个最常见的案例场景,你可以根据自己的数据情况对号入座:
比赛数据是字符串或列表(最简单)
假设比赛结果是一个字符串 "3:2" 或者一个列表 [3, 2]。
# 案例 1:字符串格式
match_result = "3:2"
# 用 ':' 分割字符串,得到 ['3', '2']
scores = match_result.split(':')
team_a_goals = int(scores[0])
team_b_goals = int(scores[1])
total_goals = team_a_goals + team_b_goals
print(f"进球总数是: {total_goals}") # 输出: 进球总数是: 5
# 案例 2:列表格式
match_scores = [3, 2]
total_goals_list = sum(match_scores) # sum() 可以直接求和
print(f"进球总数是: {total_goals_list}") # 输出: 进球总数是: 5
数据在字典或列表中(结构化数据)
实际项目中,数据通常是这样组织的:
# 案例 1:字典
match = {
"home_team": "利物浦",
"away_team": "曼联",
"home_score": 3,
"away_score": 1
}
total_goals = match["home_score"] + match["away_score"]
print(f"{match['home_team']} vs {match['away_team']} 总进球: {total_goals}")
# 案例 2:包含多场比赛的列表
matches = [
{"home": "巴萨", "away": "皇马", "h_goals": 2, "a_goals": 2},
{"home": "拜仁", "away": "多特", "h_goals": 4, "a_goals": 0}
]
# 计算每场比赛的总进球
for m in matches:
g_total = m["h_goals"] + m["a_goals"]
print(f"{m['home']} vs {m['away']}: {g_total}球")
原始文本中提取比分(正则表达式)
如果数据是网页抓取来的,包含在复杂的文本中,"巴萨 2-1 皇马" 或 "利物浦 3 : 2 曼城",可以用正则表达式 re 提取数字。
import re
text = "昨晚的比赛,巴塞罗那 2-1 皇家马德里,比赛非常精彩。"
# 使用正则找到所有数字
numbers = re.findall(r'\d+', text) # \d+ 匹配所有数字
if len(numbers) >= 2:
# 通常第一个数字是主队,第二个是客队
home_score = int(numbers[0])
away_score = int(numbers[1])
total = home_score + away_score
print(f"从文本中提取到的总进球: {total}")
else:
print("没有找到比赛比分")
从 API 或 JSON 获取(进阶)
如果是从足球 API 获取的 JSON 数据:
import json
# 模拟 API 返回的 JSON 字符串
json_data = '{"fixture": {"id": 123}, "goals": {"home": 2, "away": 1}}'
data = json.loads(json_data)
total_goals = data["goals"]["home"] + data["goals"]["away"]
print(f"API 数据进球总数: {total_goals}")
遇到实际问题怎么选?
| 你的数据长什么样? | 用哪个方法? |
|---|---|
"3:2" 或 "3-2" |
split() 分割后 int() 转换再相加 |
[3, 2] 或 (3, 2) |
sum() 函数直接求和 |
{"home": 3, "away": 2} |
字典键取值后相加 |
| 网页上的纯文本 | re.findall(r'\d+', text) 提取数字 |
| Excel 或 CSV 文件 | pandas 读取后,用列相加 |
核心思路就是:把两个分数变成整数,然后相加。
如果你能提供具体的一行数据样本(比如粘贴一个你遇到的字符串或 JSON 片段),我可以帮你写出更精准的代码。