python3-列表字典简单练习题
1.求全部元素的和[1,2,1,2,3,3,3,3] >>> a=[1,2,1,2,3,3,3,3] >>> result=0 >>> for i in a: ... result+=i ... >>> print (result) 18 2.求偶数元素的和[1,2,1,2,3,3,3,3] 方法一:只适用于当前list >>> a=[1, 2, 1, 2, 3, 3, 3, 3] >>> res=0 >>> for i in a[1:4:2]: ... res+=i ... >>> print (res) 4 方法二:适用于任何list >>> a=[1, 2, 1, 2, 3, 3, 3, 3] >>> res=0 >>> for i in a: ... if i%2==0: ... res+=i ... >>> print(res) 4 3.统计一下所有数字出现的个数[1,2,1,2,3,3,3,3] >>> d={} >>> for i in a: ... d[i]="1" ... >>> d {1: '1', 2: '1', 3: '1'} >>> d.keys() dict_keys([1, 2, 3]) >>> list(d.keys()) [1, 2, 3] >>> for i in list(d.keys()): ... print("数字"+str(i)+"共出现了:"+str(a.count(i))+"次") ... 数字1共出现了:2次 数字2共出现了:2次 数字3共出现了:4次