Python语言程序设计基础—— 组合数据类型

Posted 树的种子

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python语言程序设计基础—— 组合数据类型相关的知识,希望对你有一定的参考价值。

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)

 

以上是关于Python语言程序设计基础—— 组合数据类型的主要内容,如果未能解决你的问题,请参考以下文章

python基础(str,list,tuple)

Python基础篇_组合数据类型的基本概念

python基础

python基础篇-组合数据类型-2.序列

Python基础语法三组合数据类型

python基础===python基础知识问答(转)