Python语言程序设计基础(6)—— 组合数据类型
tuple 元组(创建后不能修改)
tuple = "cat","dog","tiger","human" print(tuple) def fun(x): return x,x*2 print(type(fun(3))) for x,y in ((2,0),(2,5),(3,8)): print(x+y)
set 集合
S = {435,"BAT",(25,"CS"),435} print(S) W = set("apple") print(W) V = set(("cat",4,"apple")) print(V)
list 列表
ls = [423,"BAT",[10,"CS"]] print(ls[2][1][1]) vlist = list(range(5)) print(vlist) print("YES") if 2 in vlist else print("NO") lss = [52,36,95,78] print(sorted(lss)) print(lss)
字典
sets = {23,35} print(type(sets)) setss = {34:23,33:22,23:32} for a in setss.keys(): print(a) ls = setss.items() print(ls) for key in setss: print(setss[key])
计算平均数,和标准差
import math def inputs() : nums = [] x = input() while x != "": nums.append(int(x)) x = input() return nums ls = inputs() print(ls) def mean(numbers): s = 0 for num in numbers: s += num return s / len(numbers) def dev(numbers,means): sdev = 0 for num in numbers: sdev += (num-means)**2 return math.sqrt(sdev/(len(numbers)-1)) print(dev(ls,mean(ls)))
统计词频(哈利波特1)
txt = open("1.Harry Potter and the Sorcerer's Stone.txt","r").read() txt = txt.lower() for ch in '",!-?;.`': txt = txt.replace(ch," ") #print(txt) ls = txt.split() print(ls) maps = {} for str in ls: maps[str] = maps.get(str,0) + 1 item = list(maps.items()) cnt = 1 for a in item : print(a,end=" ") if cnt % 10== 0: print("") cnt+=1 print("") item.sort(key=lambda x:x[1],reverse=True) for i in range(10): word ,count = item[i] print(word,count)