简体   繁体   English

通过列表中的每2个元素优化总和

[英]optimize sum by every 2 elements in list

I have a list: 我有一个清单:

mylist = [0.01, 0.09, 0.04, 0.16]

I want to take the sum every two elements, so my result will be: [0.1, 0.2] 我想每两个元素求和,所以我的结果将是: [0.1, 0.2]

I figured this solution: 我想出了这个解决方案:

chunks = [mylist[i:i + 2] for i in range(0, len(mylist), 2)]

temp = []
for i in chunks:
    s = 0
    for j in i:
        s += j
    temp.append(s)

print(temp)

[0.1, 0.2]

but I was wondering if there is a better solution avoiding the 2 for loops. 但我想知道是否有更好的解决方案,避免使用2 for循环。

Why not simply use the sum(..) builtin: 为什么不简单地使用内置的sum(..)

temp = [sum(mylist[i:i+2]) for i in range(0, len(mylist), 2)]

This is a one-liner that clearly is more Pythonic. 这是一种单行代码,显然更像Python。 Furthermore it is probably more efficient since here you do not store all slices into memory first, etc. but you directly calculate the sum. 此外,它可能更有效,因为在这里您不必先将所有切片存储到内存等中,而是直接计算总和。

map(sum, zip(mylist[::2], mylist[1::2]))

For lists of odd length, use zip_longest instead 对于奇数长度的列表,请改用zip_longest

from itertools import zip_longest as zipl
map(sum, zipl(mylist[::2], mylist[1::2], fillvalue=0))

Some people might consider it an overkill, however once you go into calculations over arrays of numbers, numpy is your friend. 有些人可能认为这是一个过大的杀伤力,但是一旦您对数字数组进行计算,numpy就是您的朋友。 It enables you to make such calculations in a readable and efficient manner. 它使您能够以可读且有效的方式进行此类计算。

import numpy as np
x = np.array([0.01, 0.09, 0.04, 0.16])
# reshaping the array to a 2D array, and summing over the columns
x.reshape((x.shape[0]/2,2)).sum(axis=1)

You can try this (Will work for both even and odd lengths): 您可以尝试使用此方法(对于偶数和奇数长度都可以使用):

import itertools as it    
[sum(r) for r in it.izip_longest(mylist [::2], mylist [1::2], fillvalue=0)]

Using iteration_utilities.grouper : 使用iteration_utilities.grouper

>>> from iteration_utilities import grouper
>>> mylist = [0.01, 0.09, 0.04, 0.16]
>>> [sum(group) for group in grouper(mylist, 2)]  # or "list(map(sum, grouper(mylist, 2)))"
[0.09999999999999999, 0.2]

That the first value isn't 0.1 is because of floating point arithmetic, the other solutions here are similarly affected. 第一个值不是0.1是由于浮点运算,这里的其他解决方案也受到类似的影响。

This should be as fast as the other approaches, maybe even faster (except for the numpy-solution). 这应该与其他方法一样快,甚至可能更快(除了numpy-solution)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM