L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
def sub_sum(L):
j_h = 0
o_h = 0
for l in L:
if l%2==1:
j_h = j_h + l
else:
o_h = o_h + l
return j_h, o_h
result = sub_sum(L)
print(result[0]) 输出为1
print(result[1]) 输出为0
各位看看有什么问题,答案的方式我不太懂
def sum_of_jo(L):
jnum=[]
onum=[]
jsum=0
osum=0
for x in L:
if(x%2==0):
onum.append(x)
else:
jnum.append(x)
for a in jnum:
jsum=jsum+a
for b in onum:
osum=osum+b
return jsum,osum
L=[1,2,3,4,5,6,8,9]
jsum,osum=sum_of_jo(L)
print('奇数项之和为={}'.format(jsum))
print('偶数项之和为={}'.format(osum))
result=sum_of_jo(L)
jsum=result[0]
osum=result[1]
print('奇数项之和为={}'.format(jsum))
print('偶数项之和为={}'.format(osum))
def sub_sum(L): index = 0 count1 = 0 count2 = 0 for x in L: if index % 2 == 0: count1 += x else: count2 += x index += 1 return count1, count2 result = sub_sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) print("所有奇数项的和为{},所有偶数的和为{}".format(result[0], result[1])) 因为你是要在列表中的所有元素都遍历完之后,才会return和的,所以return要和for对齐,不然就遍历一个元素就结束循环了
return 没有缩进,应该和for齐平
def sub_sum(L):
j_h = 0
o_h = 0
for l in L:
if l%2==1:
j_h = j_h + l
else:
o_h = o_h + l
return j_h, o_h