1. 程式人生 > >python3-列表字典簡單練習題

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次