如果第一列在Python中是相同的,如何在第二列中添加数字?

时间:2012-08-14 20:41:07

标签: python list

如果我有样本输入:

Apples,2
Apples,4
Apples,1
Oranges,10
Oranges,2

如何获得如下输出:

Apples,7
Oranges,12

感谢。

编辑:我正在使用Python 3

6 个答案:

答案 0 :(得分:2)

使用defaultdict。

from collections import defaultdict

d=defaultdict(int)
with open('inputfile') as f:
    for line in f:
        fruit,num = line.split(',')
        #could also use `fruit,num,*rest = line.split(',')` 
        #for a little more robustness at the expense of 
        #backward compatability
        d[fruit]+=int(num)

您也可以使用csv模块来解析文件中的列,但在这种情况下,这对我来说似乎有些过分。

答案 1 :(得分:2)

Counters专为此而设计。

# I'm assuming you have a list or iterable of lines like this
file="""Apples,2
Apples,4
Apples,1
Oranges,10
Oranges,2""".split('\n')

# Here's the code under that assumtion
from collections import Counter
from functools import reduce
from operator import add
tally = reduce(add, (Counter({x[0]: int(x[1])}) for x in (x.split(',') for x in file)))

# To demonstrate
for name in tallies:
print('%s,%s' % (name, tallies[name]))

答案 2 :(得分:0)

from collections import defaultdict
result = defaultdict(int)
lines = """
Apples,2
Apples,4
Apples,1
Oranges,10
Oranges,12
"""
for k in lines.splitlines():
    result[k.split(",")[0]]+=int(k.split(",")[-1] or 0)#account for '' cases...
print result

答案 3 :(得分:0)

stuff = """
Apples,2
Apples,4
Apples,1
Oranges,10
Oranges,2
"""

# Holds mapping from fruit->count    
total = {}

# Process input    
lines = stuff.strip().splitlines()

for x in lines:
    name, _, count = x.partition(",")
    total.setdefault(name, 0)
    total[name] += int(count)

# Output
for k, v in sorted(total.items()):
    print("{},{}".format(k, v))

(不要在这台机器上安装Python 3,但上面应该可以使用,可能需要进行一些小调整)

答案 4 :(得分:0)

strs="""Apples,2
Apples,4
Apples,1
Oranges,10
Oranges,2"""

dic={}
for x in strs.split():
    key=x.split(',')[0]
    val=int(x.split(',')[1])    
    dic[key]=dic.get(key,0)+val

print(dic)  #prints {'Apples': 7, 'Oranges': 12}

答案 5 :(得分:0)

不喜欢groupby?

data = """\
Apples,2
Apples,4
Apples,1
Oranges,10
Oranges,2""".splitlines()

from itertools import groupby

groups = groupby((line.split(',') for line in data), key=lambda x:x[0])
table = dict((k,sum(map(int,(x[1] for x in vals)))) for k,vals in groups)
for item in table.items():
    print '%s,%d' % item

打印:

Apples,7
Oranges,12