累积发生次数

时间:2016-04-26 15:10:13

标签: python list count

我有许多列表有2个维度,我需要得到 累积计数元素

a=[1,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4]
b=[1,1,1,2,2,2,3,3,3,4]
c=[1,2,2,2,3,4]
c=[] 
for i in a:
    for x,y in enumerate(c):
       print i
       if y[0]==i:
           y[1]+=1
       else:
           c.append([i,1])

我需要获得:

[[1,9],[2,10],[3,7]...]

4 个答案:

答案 0 :(得分:1)

您可以使用Counter

from collections import Counter

a=[1,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4]
b=[1,1,1,2,2,2,3,3,3,4]
c=[1,2,2,2,3,4]

res = Counter()
for x in (a, b, c):
    res.update(x)

print res # Counter({2: 10, 1: 9, 3: 8, 4: 5})

如果您需要结果为list而不是dict,则可以将其排序为列表:

print sorted(res.iteritems()) # [(1, 9), (2, 10), (3, 8), (4, 5)]

答案 1 :(得分:1)

另一个解决方案,仅适用于Python 3.5 +:

>>> from collections import Counter
>>> Counter([*a, *b, *c])
Counter({2: 10, 1: 9, 3: 8, 4: 5})

如果您确实需要列表格式列表,则转换如下:

>>> [list(x) for x in Counter([*a, *b, *c]).items()]
[[1, 9], [2, 10], [3, 8], [4, 5]]

答案 2 :(得分:1)

你应该使用counter和itertools:

from collections import Counter
import itertools

a = [1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4]
b = [1, 1, 1, 2, 2, 2, 3, 3, 3, 4]
c = [1, 2, 2, 2, 3, 4]

# this will iterate through the 3 lists in sequence, and count the number of occurrences of each element
res = Counter(itertools.chain(a, b, c))

[[key, value] for key, value in res.items()]

结果:

[[1, 9], [2, 10], [3, 8], [4, 5]]

答案 3 :(得分:-1)

有两种方法可以做到。

int foo( std::shared_ptr<double>& bar ) {
    ...
    std::shared_ptr<double> p( my_allocator<double>::allocate(), my_deleter<double>() );
    bar.swap(p); // this copies the deleter
    ...
}

int main( int, char** ) {
    std::shared_ptr<double> d;
    foo( d ); // d now has a new deleter that will be called when it goes out of scope
    ...
}
from operator import add
from functools import reduce
from collections import Counter
reduce(add, (Counter(l) for l in (a,b,c)))
# Counter({1: 9, 2: 10, 3: 8, 4: 5})