一: #計算平均數,中位數和眾數 #coding:utf-8 #計算平均數,中位數和眾數 import randomlst = [random.randint(0,10) for i in range(11)]s = sum(lst)length = len(lst)average = s*1.0 ...
一:
#計算平均數,中位數和眾數
#coding:utf-8
#計算平均數,中位數和眾數
import random
lst = [random.randint(0,10) for i in range(11)]
s = sum(lst)
length = len(lst)
average = s*1.0 / length
print "The average is:",average
lst.sort()
print "From small to bigger,",lst
middle = lst[length/2]
print "middle",middle
#眾數 method1
m = {}
for i in lst:
if i in m:
m[i] +=1
else:
m[i] = 1
print m
max_number = max(m.values())
print max_number
for k,v in m.items():
if v == max_number:
print "mode is:",k
#眾數method2
t = set(lst)
d = {}
for i in t:
d[i] = lst.count(i)
print d
for k,v in m.items():
if v == max_number:
print "mode is:",k
二:
一列表由若幹個整數組成,現要將偶數放到前面,奇數放在後面
#coding:utf-8
#一列表由若幹個整數組成,現要將偶數放到前面,奇數放在後面
import random
lst = [random.randint(0,100) for i in range(90)]
print lst
odd = []
even = []
for i in lst:
if i%2 ==0:
even.append(i)
else:
odd.append(i)
print even
print odd
even.extend(odd)
print "result:",even
三:
列表中的字元串按照指定字元順序排序
#coding:utf-8
#對列表中的字元串按照指定字元順序排序
by_string = ["a","e","i","o","u"]
words = ["suzhou","shanghai","hangzhou","nanjing","beijing"]
result = {}
for word in words:
n = []
for i in word:
if i in by_string:
n.append(by_string.index(i))
else:
n.append(9)
result[word] = n
print result
vs = result.values()
vs.sort()
print vs
sorted_word = []
for i in vs:
for k,v in result.items():
if v == i:
sorted_word.append(k)
print sorted_word