首页 > 解决方案 > Python中的求和值

问题描述

我正在尝试获取这样的列表,其中两个收集的数字相加并提供该总和的最终结果team1Goals + team2Goals

FT      4 + 1 - Atletico El Vigia v Llaneros de Guanare
Postp.  1 + 2 - Deportivo Lara B v Atletico El Vigia
Postp.  0 + 0 - Llaneros de Guanare v Urena SC
FT      1 + 0 - Rayo Zuliano v Universidad de Los Andes FC

预期结果:

FT      5 - Atletico El Vigia v Llaneros de Guanare
Postp.  3 - Deportivo Lara B v Atletico El Vigia
Postp.  0 - Llaneros de Guanare v Urena SC
FT      1 - Rayo Zuliano v Universidad de Los Andes FC

我尝试使用该sum()方法,但它给了我一个错误,甚至给了我一个我真的不知道如何使用的提示:

TypeError: sum() 不能对字符串求和 [使用 ''.join(seq) 代替]

    response = requests.get(url, headers=headers).json()
    stages = response['Stages']
    for stage in stages:
        events = stage['Events']
        for event in events:
            outcome = event['Eps']
            team1Name = event['T1'][0]['Nm']
            if 'Tr1OR' in event.keys():
                team1Goals = event['Tr1OR']
            else:
                team1Goals = '0'
            
            team2Name = event['T2'][0]['Nm']
            if 'Tr2OR' in event.keys():
                team2Goals = event['Tr2OR']
            else:
                team2Goals = '0'
            print('%s\t%s - %s v %s' %(outcome, [sum(team1Goals,team2Goals)], team1Name, team2Name))

标签: python

解决方案


所以,总和只适用于整数,加整数,这就是错误所说的,并且也有解决方案

利用:variable_name = str(team1Goals) + str(team2Goals)


推荐阅读