def sub_sum(L): index = 0 sum1 = 0 sum2 = 0 for item in L: if index % 2 == 0: sum1 += item else: sum2 += item index += 1 return sum1, sum2 L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] result = sub_sum(L) print('奇数项的和 = {}'.format(result[0])) print('偶数项的和 = {}'.format(result[1]))
用来判断list每一项是奇数项还是偶数项的,index%2如果等于0,那就是偶数项,如果不等于0,那就是奇数项