遍历列表并获取偶数和奇数

Iterating through list and getting even and odd numbers

还有一个我似乎有问题的练习。我会说我做对了,但 Python 知道得更多。

任务正文是:

Write a function that takes a list or tuple of numbers. Return a two-element list, containing (respectively) the sum of the even-indexed numbers and the sum of the odd-indexed numbers. So calling the function as even_odd_sums([10, 20, 30, 40, 50, 60]) , you’ll get back [90, 120] .

我的代码是:

def even_odd_sums(sequence):
    sum_list = []
    for i, v in enumerate(sequence):
        if i % 2 == 0:
           sum_list = sum_list.insert(0, sum(v))
        else:
           sum_list = sum_list.insert(1, sum(v))
    return sum_list

print(even_odd_sums([10,20,30,40,50,60]))

结果是:

TypeError                                 Traceback (most recent call last)
<ipython-input-60-14518295929c> in <module>
----> 1 print(even_odd_sums([10,20,30,40,50,60]))

<ipython-input-59-51fcb6e9a115> in even_odd_sums(sequence)
      3     for i, v in enumerate(sequence):
      4         if i % 2 == 0:
----> 5            sum_list = sum_list.insert(0, sum(v))
      6         else:
      7            sum_list = sum_list.insert(1, sum(v))

TypeError: 'int' object is not iterable

我试图在 Google 上找到解决方案,我尝试了其他方法来解决此任务(“for i in range(len(sequence))”,但我无法解决不可迭代对象问题

提前致谢!

正如已经指出的那样,sum 需要一个可迭代对象,而不是一个数字。因此,使用循环方法,您可以继续添加适当的总和:

def even_odd_sums(sequence):
    sum_list = [0, 0]
    for i, v in enumerate(sequence):
        sum_list[i % 2] += v
    return sum_list

或者,您可以对适当的切片进行更简单的求和:

def even_odd_sums(sequence):
    return [sum(sequence[::2]), sum(sequence[1::2])]

最简单的方法。使用切片和索引。

def even_odd_sums(lists):
    return [sum(lists[::2]),sum(lists[1::2])]
print(even_odd_sums([10,20,30,40,50,60]))

你可以试试:

def even_odd_nums(sequence):
return [sum([item for index, item in enumerate(sequence) if index % 2 == 0]), sum([item for index, item in enumerate(sequence) if index % 2 != 0])]

干脆尝试使用切片和索引。这是一个我们都容易忘记使用的好工具。

def even_odd_sums(lists):
    return [sum(lists[::2]),sum(lists[1::2])]