0

我有三列包含大量数据,第一列有 id,第三列有值。id 中有重复项,但值中没有。我想从 id 的列中删除重复项,但想要所有值的总和。例如 id class_code 值 a = 1 b * 2 c + 3 a + 4 d = 5 b + 6 a = 7 a + 8 b * 9

想要像这样的输出

a   8
a   12
b   11
c   3
d    5

仅删除具有相同 class_codes 和 id 并添加值的那些,在此操作之后打印整个列表,还删除具有标题的第一行。我试过了,但它从表中删除了整个值

file="C:/Python25/ref.txt"
fh=open(file,'r')
myData=fh.read()
myText=myData.split()
line_seen=set()
for line in myText:
    if line in line_seen:
        line_seen.add(line)
            print line[0:]

fh.close()
4

3 回答 3

1
d = {}
with open('your_file', 'r') as f:
    for line in f.readlines():
        line = line.split()
        if line[0] in d:
            d[line[0]] += int(line[2])
        else:
            d[line[0]] = int(line[2])
  1. 逐行读取文件。
  2. id如果不存在,则插入字典。
  3. 如果存在则更新字典id
  4. 繁荣!完毕。
于 2013-11-11T11:56:32.453 回答
0
from collections import defaultdict

d = defaultdict(int)
for line in open('ref.txt'):
    key, value = line.split()
    d[key] += int(value)

print sorted(d.items())

[('a', 20), ('b', 17), ('c', 3), ('d', 5)]

于 2013-11-11T12:43:50.327 回答
0

很容易,当你使用字典时。像这样的东西应该可以工作(未经测试):

D = dict()
for line in myText:
    if line[0] not in D.keys():
        D[line[0]] = line[1])
    else
        D[line[0]] = D[line[0]] + line[1])
于 2013-11-11T11:17:03.227 回答