python左右合并数据_Python:合并统计数据

Okay - I'm sure this has been answered here before but I can't find it....

My problem: I have a list of lists with this composition

0.2 A

0.1 A

0.3 A

0.3 B

0.2 C

0.5 C

My goal is to output the following:

0.6 A

0.3 B

0.7 C

In other words, I need to merge the data from multiple lines together.

Here's the code I'm using:

unique_percents = []

for line in percents:

new_percent = float(line[0])

for inner_line in percents:

if line[1] == inner_line[1]:

new_percent += float(inner_line[0])

else:

temp = []

temp.append(new_percent)

temp.append(line[1])

unique_percents.append(temp)

break

I think it should work, but it's not adding the percents up and still has the duplicates. Perhaps I'm not understanding how "break" works?

I'll also take suggestions of a better loop structure or algorithm to use. Thanks, David.

解决方案

You want to use a dict, but collections.defaultdict can come in really handy here so that you don't have to worry about whether the key exists in the dict or not -- it just defaults to 0.0:

import collections

lines = [[0.2, 'A'], [0.1, 'A'], [0.3, 'A'], [0.3, 'B'], [0.2, 'C'], [0.5, 'C']]

amounts = collections.defaultdict(float)

for amount, letter in lines:

amounts[letter] += amount

for letter, amount in sorted(amounts.iteritems()):

print amount, letter

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值