Python:合并计数数据
好的 - 我确信这个问题以前已经在这里得到过回答,但我找不到它......
我的问题:我有一个包含此成分的列表
0.2 A
0.1 A
0.3 A
0.3 B
0.2 C
0.5 C
我的目标是输出以下内容:
0.6 A
0.3 B
0.7 C
换句话说,我需要将多行数据合并在一起。
这是我正在使用的代码:
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
我认为它应该可以工作,但它没有将百分比相加,并且仍然有重复项。也许我不明白“休息”是如何运作的?
我还将采纳更好的循环结构或算法的建议。谢谢,大卫。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
您想使用字典,但是
collections.defaultdict
在这里非常方便,这样您就不必担心字典中是否存在该键 - 它只是默认为 0.0 :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:试试这个:
Try this out:
由于所有字母等级都分组在一起,因此您可以使用 itertools.groupby (如果没有,只需提前对列表进行排序即可):
给出:
Since all of the letter grades are grouped together, you can use itertools.groupby (and if not, just sort the list ahead of time to make them so):
Gives:
如果您有这样的列表列表:
[ [0.2, A], [0.1, A], ...]
(事实上,它看起来像一个元组列表:)If you have a list of lists like this:
[ [0.2, A], [0.1, A], ...]
(in fact it looks like a list of tuples :)使用
collections.defaultdict
计算值(假设
d
中的文本数据):Using
collections.defaultdict
to tally values(assuming text data in
d
):如果您使用的是 Python 3.1 或更高版本,则可以使用 collections.Counter。我还建议使用 decimal.Decimal 而不是浮点数:
结果是:
If you are using Python 3.1 or newer, you can use collections.Counter. Also I suggest using decimal.Decimal instead of floats:
The result is:
这很冗长,但有效:
This is verbose, but works:
假设我们有这个,
您现在可以遍历这个和 sum
或将值组合在一起并使用 sum:
Lets say we have this
You can now just go though this and sum
Or group values together and use sum: