Python Dict列表到整数的总和

时间:2015-07-27 14:24:57

标签: python list dictionary casting int

所以我有一系列列表,我想总结并返回每个值。列表如下所示:

'testRel.txt': [1, 1, 1, 1, 1]

这是我最近的回溯:

Traceback (most recent call last):
File "./SeriesCount.py", line 24, in <module>
w.writerow(sum(series))
TypeError: unsupported operand type(s) for +: 'int' and 'str'

我知道为什么它不能总结我的价值观(他们不是整数,因此无法总结),我只是在修改我的列表的语法时遇到问题整数的关键值。这是脚本:

#!/usr/bin/env python

import csv
import copy
import os
import sys
import glob

#get current working dir, set count, and select file delimiter
os.chdir('/mypath')

#parses through files and saves to a dict
series = {}
for fn in glob.glob('*.txt'):
    with open(fn) as f:
        series[fn] = [1 for line in f if line.strip() and not line.startswith('#')]

print series

#save the dictionary with key/val pairs to a csv
with open('seriescount.csv', 'wb') as f:
    w = csv.DictWriter(f, series) 
    w.writeheader()
    w.writerow(sum(series))

结果应如下所示:

'testRel.txt': 5

2 个答案:

答案 0 :(得分:2)

您的代码中几乎没有问题 -

  1. 执行sum(series)时,实际上是在尝试对键进行求和,而不是值。此外,DictWriter的编剧还希望将字典作为输入,而不是单个值(这是sum()将返回的值,如果它完全可以工作,那么无论如何都不会。)

  2. 您不应该打开文件(以二进制模式写入csv - wb),以写入模式打开它 - w

  3. 而不是做 - sum(series) - 你应该尝试字典理解来创建每个键/值对的总和。

    代码 -

    with open('seriescount.csv', 'w') as f:
        w = csv.DictWriter(f, series)
        w.writeheader()
        w.writerow({k:sum(v) for k,v in series.items()})
    

    演示 -

    >>> series = {
    ... 'mytext1.txt':[1,1,1,1,1,1],
    ... 'mytext2.txt':[1,1,1,1,1],
    ... 'mytext3.txt':[1,1,1,1,1,1,1,1,1,1,1,1]}
    >>> with open('seriescount.csv', 'w') as f:
    ...     w = csv.DictWriter(f, series)
    ...     w.writeheader()
    ...     w.writerow({k:sum(v) for k,v in series.items()})
    ...
    8
    

    seriescount.csv中的结果是 -

    mytext3.txt,mytext2.txt,mytext1.txt
    12,5,6
    

答案 1 :(得分:0)

仔细查看DictWriter类的文档:

https://docs.python.org/2/library/csv.html#csv.DictWriter

那里有一行:&#34;注意,与DictReader类不同,DictWriter的fieldnames参数不是可选的。&#34;

我相信你的问题就在这一行:

 w = csv.DictWriter(f, series)  

您的series是一个字典对象。这是构造函数参数的错误类型。你想要的是字典的字段名称列表:你想要字典的(按照你想要打印的值的顺序)。对我来说,字典中的值看起来像int值,因此不是问题。