Python类-+不支持的操作数类型:'int'和'str'

问题描述 投票:0回答:2

在Google表格中,我有一个包含用户回复的列表。根据Google API,我正在从Google表格中获取数据并将其放入python列表中。

然后我定义了一个类,在这个类中,我正在计算值的分数。调用coreCalc()时,出现以下错误消息:

Traceback (most recent call last):
  File "coreCalc.py", line 52, in <module>
    coreCalc()
  File "coreCalc.py", line 49, in __init__
    print(sum(df_array))
TypeError: unsupported operand type(s) for +: 'int' and 'str'

我该如何解决这个问题,我的课堂定义不正确,因此无法避免此错误?

我的代码[对不起,是我从VIM复制的格式]:

  7 #references
  8 import gspread
  9 from oauth2client.service_account import ServiceAccountCredentials
 10 import pandas as pd
 11 import csv
 12 import time
 13 import requests
 14 
 15 #use creds to create a client to interact with the Google Drive API
 16 scope = ['https://spreadsheets.google.com/feeds',
 17          'https://www.googleapis.com/auth/drive']
 18 creds = ServiceAccountCredentials.from_json_keyfile_name('/Users/Miauw/Miaauw/github/ComplexService/Token/client_secret.json', scope)
 19 client = gspread.authorize(creds)
 20 
 21 # Find a workbook by name and open the first sheet
 22 sheet = client.open("IFTTT_Webhooks_Events").sheet1
 23 
 24 #get data directly from google sheet.
 25 data = sheet.get_all_values()
 26 headers = data.pop(0)
 27 # capture data into dataframe
 28 df = pd.DataFrame(data, columns=headers)
 29 # obtain values from the last row of the spreadsheet. 
 30 df_array = [ (df["Statement 1"].iloc[-1]),
 31     (df["Statement 2"].iloc[-1]),
 32     (df["Statement 3"].iloc[-1]),
 33     (df["Statement 3"].iloc[-1])
 34 ]
 35 
 36 #function for calculating user lonelienss based on UCLA Lonliness scoring (theory) 
 37 class coreCalc:
 38     def __init__(self):
 39     #assign loneliness-scores to the various user-responses
 40         for i in range(len(df_array)):
 41             if df_array[i] == 'Often':
 42                 df_array[i] = 3
 43             elif df_array[i] == 'Sometimes':
 44                 df_array[i] = 2
 45             elif df_array[i] == 'Rarely':
 46                 df_array[i] = 1
 47             elif df_array[i] == 'Never':
 48                 df_array[i] = 0
 49             #obtain sum of values for final scoring
 50                 print(sum(df_array))
 50 
 51
 52  coreCalc()

其他信息:

如果我打印(df_array),结果是:

['Often', 'Never', 'Never', 'Never']

分配分数后,我得到:

[3, 0, 0, 0]

并且这是我要sum()的最后一个列表。

python python-3.x
2个回答
1
投票

只需将打印总和带出for循环,以便在计算最终分数之前将所有字符串都转换为整数

def __init__(self):
#assign loneliness-scores to the various user-response
     for i in range(len(df_array)):
         if df_array[i] == 'Often':
             df_array[i] = 3
         elif df_array[i] == 'Sometimes':
             df_array[i] = 2
         elif df_array[i] == 'Rarely':
             df_array[i] = 1
         elif df_array[i] == 'Never':
              df_array[i] = 0
     #obtain sum of values for final scoring
     print(sum(df_array))

-1
投票
temp_list = []    
for i in range(len(df_array)):
    if df_array[i] == 'Often':
        temp_list.append(3)
    elif df_array[i] == 'Sometimes':
        temp_list.append(2)
    elif df_array[i] == 'Rarely':
        temp_list.append(1)
    elif df_array[i] == 'Never':
        temp_list.append(0)
print(sum(temp_list))
© www.soinside.com 2019 - 2024. All rights reserved.