Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python:对列表中的相似值求和_Python_List_Sum - Fatal编程技术网

python:对列表中的相似值求和

python:对列表中的相似值求和,python,list,sum,Python,List,Sum,是否有一种简单的方法可以使用列表理解来求列表中所有相似值的和 i、 e.投入: [1, 2, 1, 3, 3] 预期产出: [6, 2, 2] (sorted) 我尝试使用zip,但它只适用于最多2个类似值: [x + y for (x, y) in zip(l[:-1], l[1:]) if x == y] 代码的解释 首先使用sorted(a) 执行此操作以生成类似元素的groupf 每组使用sum() 你们可以用柜台 from collections import Counter [

是否有一种简单的方法可以使用列表理解来求列表中所有相似值的和

i、 e.投入:

[1, 2, 1, 3, 3]
预期产出:

[6, 2, 2] (sorted)
我尝试使用zip,但它只适用于最多2个类似值:

[x + y for (x, y) in zip(l[:-1], l[1:]) if x == y]
代码的解释

  • 首先使用
    sorted(a)

  • 执行此操作以生成类似元素的groupf

  • 每组使用
    sum()
  • 你们可以用柜台

    from collections import Counter
    [x*c for x,c in Counter([1, 2, 1, 3, 3]).items()]
    

    您可以使用
    collections.Counter
    为此,这将花费
    O(N)
    时间:

    >>> from collections import Counter
    >>> lst = [1, 2, 1, 3, 3]
    >>> [k*v for k, v in Counter(lst).iteritems()]
    [2, 2, 6]
    

    这里
    Counter()
    返回每个唯一项的计数,然后我们将这些数字与它们的计数相乘,得到总和。

    不应该是这样;打印已排序([groupby(排序(a))中i、g的总和(g)],反向=真)?否则,我会看到TypeError:“list”对象不是callable@myildirim请现在检查。我已经测试过了。我没有收到任何错误我喜欢柜台的方式:)
    >>> from collections import Counter
    >>> lst = [1, 2, 1, 3, 3]
    >>> [k*v for k, v in Counter(lst).iteritems()]
    [2, 2, 6]