Python 字典列表到整数总和

Python Dict List to Sum of ints

所以我有一系列列表,我想对其进行总结,return 每个单独的值。列表如下所示:

'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

好好看看 DictWriter 的文档 class:

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

那里有一行内容是:"Note that unlike the DictReader class, the fieldnames parameter of the DictWriter is not optional."

我认为您的问题出在这一行:

 w = csv.DictWriter(f, series)  

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

您的代码中存在一些问题 -

  1. 当您执行 sum(series) 时,您实际上是在尝试对键求和,而不是对值求和。此外,DictWriter 的 writerow 需要一个字典作为输入,而不是单个值(这是 sum() 会 return,如果它可以工作,无论如何都不会)。

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

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

代码-

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