Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python问题将dict汇总到列表中_Python_Python 2.7_Dictionary - Fatal编程技术网

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])