代码:
def sum_list(n): result=0 for i in n: result+=i return result list1=[1,2,3,4] list2=[17,5,3,5] print(f"The sum of {list1} is:" ,sum_list(list1)) print(f"The sum of {list2} is:" ,sum_list(list2)) print(f"The sum of {list1} is:" ,sum(list1)) print(f"The sum of {list2} is:" ,sum(list2))
效果:
The sum of [1, 2, 3, 4] is: 10 The sum of [17, 5, 3, 5] is: 30 The sum of [1, 2, 3, 4] is: 10 The sum of [17, 5, 3, 5] is: 30
总结:
- f"{list1}",显示的是列表1里面的数据[1,2,3,4],sum_list(list1)调用函数,将list1的数据传递给n,然后返回result值;
- sum(list1)直接实现相加;
- for i in n:
result+=i 计算列表里面的每个数据,不需要i+=1;
for i in range(0,n+1): 计算列表对应的个数 result+=n**2