前提:Python的列表解析式
[expression for iter_var in iterable1 if condition]
import random a=[random.randint(1,99) for i in range(10) if random.randint(1,99)<40] print(a)
等价于下面的意思:
import random a=[] for i in range(10): if random.randint(1,99)<40: a.append(random.randint(1,99)) print(a)
1、计算平均数,中位数和众数
中位数:中间的数字
众数:出现次数最多的数字
求平均数:使用sum函数直接求列表的值
import random a=[random.randint(1,99) for i in range(10)] print(a,len(a)) avg = sum(a)*1.0/len(a) print("The avg is:",avg)
[69, 4, 84, 17, 46, 14, 9, 41, 49, 23] 10 The avg is: 35.6
求中位数:中位数需要将列表排序,如果数字个数是奇数,取中间即可,如果是偶数,取中间两个值的平均数即可。
import random li=[random.randint(1,15) for i in range(10)] li.sort() print(li) remainder = len(li)%2 mid_1 = len(li)/2 -1 mid = len(li)/2 if (remainder == 0): print((li[int(mid_1)]+li[int(mid)])/2*1.0) else: print(li[int(mid)])
[2, 3, 4, 5, 7, 9, 10, 11, 13, 14]
8.0
求众数:
import random li=[random.randint(1,15) for i in range(10)] print(li) dic = {} for i in li: k,v = i,li.count(i) dic[k]=v print(dic) for k,v in dic.items(): if (v == max(dic.values())): print(k,v)
[1, 5, 4, 10, 5, 10, 7, 3, 12, 12] {1: 1, 5: 2, 4: 1, 10: 2, 7: 1, 3: 1, 12: 2} 5 2 10 2 12 2
2、一个列表若干整数构成,现在要将偶数放在前面,奇数放在后面
import random li=[random.randint(1,15) for i in range(10)] odd=[] even=[] print(li) for i in range(len(li)): if (li[i]%2==0): even.append(li[i]) else: odd.append(li[i]) even.extend(odd) print(even) [4, 2, 5, 5, 14, 6, 8, 1, 15, 4] [4, 2, 14, 6, 8, 4, 5, 5, 1, 15]
3、斐波拉切数列
F(0)=0
F(1)=1
F(2)=F(1)+F(0)
def fab(n): if(n>=2): return fab(n-1)+fab(n-2) else: return n for i in range(8): print(fab(i), end=' ') 0 1 1 2 3 5 8 13