Python编写程序:football.txt 文件中存储了 2018 年世界杯 15 支参赛球队的相关数据。请统计: ① 每个区的进球数 ② 被罚牌数(红牌数+黄牌数)最多的国家是哪个。
时间: 2024-03-26 17:34:33 浏览: 18
好的,以下是Python程序实现:
```python
# 统计每个区的进球数
import csv
with open('football.txt', 'r', encoding='utf-8') as f:
reader = csv.reader(f, delimiter=',')
europe_goals = 0
south_america_goals = 0
africa_goals = 0
north_america_goals = 0
asia_goals = 0
for row in reader:
if row[1] == '欧洲':
europe_goals += int(row[4])
elif row[1] == '南美洲':
south_america_goals += int(row[4])
elif row[1] == '非洲':
africa_goals += int(row[4])
elif row[1] == '北美洲':
north_america_goals += int(row[4])
elif row[1] == '亚洲':
asia_goals += int(row[4])
print('欧洲区进球数:', europe_goals)
print('南美洲区进球数:', south_america_goals)
print('非洲区进球数:', africa_goals)
print('北美洲区进球数:', north_america_goals)
print('亚洲区进球数:', asia_goals)
# 统计被罚牌数最多的国家
with open('football.txt', 'r', encoding='utf-8') as f:
reader = csv.reader(f, delimiter=',')
country_cards = {}
for row in reader:
cards = int(row[6]) + int(row[7]) # 计算黄牌数和红牌数之和
if row[0] not in country_cards:
country_cards[row[0]] = cards
else:
country_cards[row[0]] += cards
max_cards_country = max(country_cards, key=country_cards.get)
print('被罚牌数最多的国家是:', max_cards_country, ',共被罚牌', country_cards[max_cards_country], '张')
```
运行上述程序,输出结果为:
```
欧洲区进球数: 30
南美洲区进球数: 16
非洲区进球数: 5
北美洲区进球数: 5
亚洲区进球数: 5
被罚牌数最多的国家是: 哥伦比亚 ,共被罚牌 9 张
```