简体   繁体   中英

Adding elements in a list in Python

I have a list a=[1,2,3,4,5,6]

I would like to create a function that sums every n elements together in a new list for example

my_sum(a,2)=[3,7,11] - a new list with a[0]+a[1], a[2]+a[3]

my_sum(a,3)=[6,15] - a[0]+a[1]+a[2],

I am stuck, anyone got an idea?

Try this:

def my_sum(a, n):
    return [sum(a[i: i + n]) if len(a[i: i + n]) >= n else None for i in range(0, len(a), n)]
a=[1,2,3,4,5,6]
my_sum(a, 4)

Perhaps this is what you're looking for, also quite readable:

def my_sum(array, n):
    result = []
    if n > len(array):
        return []
    for i in range(0, len(array), n):
        result.append(sum(array[i:i+n]))

    return result

ls = [1,2,3,4,5,6]
print(my_sum(ls, 5))

You can try this:

def my_sum(a, b):
    sum = 0
    new_list = []
    lenght = len(a)
    if lenght % b == 0:
        for count, value in enumerate(a):
            if count + 1 == lenght:
                sum += value
                new_list.append(sum)
            elif count != 0 and count % b == 0:
                new_list.append(sum)
                sum = 0
                sum += value
            else:
                sum += value
        return new_list
    else:
        print("It's not possible")
        return

You can do this only If the number of the sum is divisible by the list lenght (this is the reason for the first "If").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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