creating sum of odd indexes python

后端 未结 2 418
醉话见心
醉话见心 2020-12-07 03:28

I\'m trying to create a function equal to the sum of every other digit in a list. For example, if the list is [0,1,2,3,4,5], the function should equal 5+3+1. How could I do

相关标签:
2条回答
  • 2020-12-07 04:04

    Here is a simple one-liner:

    In [37]: L
    Out[37]: [0, 1, 2, 3, 4, 5]
    
    In [38]: sum(L[1::2])
    Out[38]: 9
    

    In the above code, L[1::2] says "get ever second element in L, starting at index 1"

    Here is a way to do all the heavy lifting yourself:

    L = [0, 1, 2, 3, 4, 5]
    total = 0
    for i in range(len(L)):
        if i%2:  # if this is an odd index
            total += L[i]
    

    Here's another way, using enumerate:

    L = [0, 1, 2, 3, 4, 5]
    total = 0
    for i,num in enumerate(L):
        if i%2:
            total += num
    
    0 讨论(0)
  • 2020-12-07 04:06
    >>> arr = [0,1,2,3,4,5]
    >>> sum([x for idx, x in enumerate(arr) if idx%2 != 0])
    9
    

    This is just a list comprehension that only includes elements in arr that have an odd index.

    To illustrate in a traditional for loop:

    >>> my_sum = 0
    >>> for idx, x in enumerate(arr):
    ...     if idx % 2 != 0:
    ...         my_sum += x
    ...         print("%d was odd, so %d was added. Current sum is %d" % (idx, x, my_sum))
    ...     else:
    ...         print("%d was even, so %d was not added. Current sum is %d" % (idx, x, my_sum))
    ... 
    0 was even, so 0 was not added. Current sum is 0
    1 was odd, so 1 was added. Current sum is 1
    2 was even, so 2 was not added. Current sum is 1
    3 was odd, so 3 was added. Current sum is 4
    4 was even, so 4 was not added. Current sum is 4
    5 was odd, so 5 was added. Current sum is 9
    
    0 讨论(0)
提交回复
热议问题