Python问题将dict汇总到列表中
我有一个字典(有多个对象),我试图创建一个列表,对每个对象的一些值求和。到目前为止,我已经:Python问题将dict汇总到列表中,python,python-2.7,dictionary,Python,Python 2.7,Dictionary,我有一个字典(有多个对象),我试图创建一个列表,对每个对象的一些值求和。到目前为止,我已经: import csv,os,re #numpy.corrcoef(list1, list2)[0, 1] input_dict = csv.DictReader(open("./MCPlayerData/AllPlayerData2.csv")) npi_scores=[] for person in input_dict: #print person i=0 for key
import csv,os,re
#numpy.corrcoef(list1, list2)[0, 1]
input_dict = csv.DictReader(open("./MCPlayerData/AllPlayerData2.csv"))
npi_scores=[]
for person in input_dict:
#print person
i=0
for key in person:
if re.match(r'npi[0-9]+', key):
#print key,'=',person[key] #returns npi0=1,npi1=3,npi3=2,etc
try:
i+=person[key]
#print(person[key])
except TypeError:
i="NA" #returns NA because one of the values wasnt filled out with an integer
break
npi_scores.append(i)
break
print npi_scores #returns sum of npi scores for one person
print('DONE')
当我运行此代码时,根据第一个元素得到
NA
。这就是我所期望的,如果值不是一个整数,但是所有的值都肯定是整数。有什么想法吗?将person[key]转换为整数int(person[key])
,否则将被视为字符串
digit_str = person[key]
# checks value only consists of digits
if digit_str.isdigit():
# converts digits-only value to integer
i += int(digit_str)
你是说i+=int(person[key])
?