[英]python3 summarize elements form list of lists
I have a list of lists 我有一个清单清单
lst = [[0,1],[1,1],[3,1],[1,2],[1,3],[3,5]]
I want to summarize the second items of the sublists for equal first items. 我想将子列表的第二项归纳为相等的第一项。 The result should look like 结果应该看起来像
lst = [[0,1],[1,6],[3,6]]
I tried something like this: 我尝试过这样的事情:
lst=[[0, 0.25], [1, 0.125], [2, 0.0625], [3, 0.0625], [1, 0.125], [2, 0.0625], [3, 0.03125], [4, 0.03125]]
for listitem in range(len(lst)):
first=listitem[0]
second = 0
for obj in lst:
if obj[0] == first:
second += obj[1]
lst.remove(obj)
listitem[1] = second
Using defaultdict 使用defaultdict
from collections import defaultdict
lst=[[0, 0.25], [1, 0.125], [2, 0.0625], [3, 0.0625], [1, 0.125], [2, 0.0625], [3, 0.03125], [4, 0.03125]]
res = defaultdict(int)
for el in lst:
res[el[0]] += el[1]
res_list = [[k,v] for (k,v) in res.items()]
print(res_list)
[[0, 0.25], [1, 0.25], [2, 0.125], [3, 0.09375], [4, 0.03125]]
groupby
returns a key and iterator over the items with the same key. groupby
返回一个密钥,并在具有相同密钥的项目上进行迭代。 It must be passed a list sorted by the same key: 必须将按相同键排序的列表传递给它:
from itertools import groupby
from operator import itemgetter
lst = [[0,1],[1,1],[3,1],[1,2],[1,3],[3,5]]
result = [[k,sum(b for a,b in g)]
for k,g in groupby(sorted(lst),key=itemgetter(0))]
print(result)
Output: 输出:
[[0, 1], [1, 6], [3, 6]]
Another way to think about this is that the first item in each pair is the key
, and the second is the value
-- so if you create a dict
you can then add the values together as you come across each key -- and it's even easier if you use a defaultdict
: 另一种思考方式是每对中的第一项是key
,第二项是value
-因此,如果创建dict
,则可以在遇到每个键时将值加在一起-甚至如果使用defaultdict
更容易:
from collections import defaultdict
summary = defaultdict(int)
for sublist in lst:
key, value = sublist
summary[key] += value
print(summary.items())
The line summary[key] += value
is the workhorse here. summary[key] += value
是这里的主力军。 What it does: 它能做什么:
key
in summary 在摘要中查找key
int
to create the default value 如果不存在,则添加它并使用int
来创建默认值 summary
under key
将其存储回key
下的summary
range(n)
produces a list such as [0,1,2...n-1]
, so the type of listitem
is int
rather than list
. range(n)
产生一个列表,例如[0,1,2...n-1]
,所以listitem
的类型是int
而不是list
。
lst=[[0, 0.25], [1, 0.125], [2, 0.0625], [3, 0.0625], [1, 0.125], [2, 0.0625], [3, 0.03125], [4, 0.03125]]
for listitem in lst:
first = listitem[0]
second = 0
for obj in lst:
if obj[0] == first:
second += obj[1]
lst.remove(obj)
listitem[1] = second
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.