1. 程式人生 > 實用技巧 >Python資料型別之基礎記。。。

Python資料型別之基礎記。。。

資料型別

1、什麼是資料?為何要有資料?

==> x=10,10是我們要儲存的資料 。資料是用來表示狀態的,不同的狀態就應該用不同的型別的資料去表示

2、資料型別

A*數字(整型,長整型,浮點型,複數)

B*字串

C*列表

D*元組

E*字典

F*集合

3、資料的使用一般是按照以下幾點展開

#======================================基本使用======================================
#1、用途

#2、定義方式

#3、常用操作+內建的方法

#======================================該型別總結====================================
#存一個值or存多個值

#有序or無序

#可變or不可變(1、可變:值變,id不變。可變==不可hash 2、不可變:值變,id就變。不可變==可hash)
#AAA* 一:整型int

# ======================================基本使用======================================

# 1、用途:年齡、個數、號碼、出生年等

# 2、定義方式

# age = 18 # age = int(18)

# int功能可以把純數字的字串轉換成int型別

# res = int("18")

# # res = int("1.8")

# print(type(res))

# 瞭解(***)

# print(bin(11)) # 0b1011

# print(oct(11)) # 0o13

# print(hex(11)) # 0xb

# 3、常用操作+內建的方法

# 算數運算子與比較運算

# 二:浮點型float

# ======================================基本使用======================================

# 1、用途:薪資、身高、體重等

# 2、定義方式

salary = 3.1 # salary = float(3.1)

# float功能可以把浮點陣列成的字串轉換成float型別

# res = float("1.8")

# print(type(res))


# 3、常用操作+內建的方法

# 算數運算子與比較運算

# ======================================該型別總結====================================

# 存一個值

# 不可變
# ======================================基本使用======================================

#BBB 1、用途:記錄描述性質的狀態,例如名字、性別、國籍等

# 2、定義方式:在引號('',"",'''''',""""""")內包含一串字串

s = "hello" # s = str("hello")

# str功能可以把任意型別轉換成str型別

# res=str([1,2,3]) # "[1,2,3]"

# print(type(res))

# 3、常用操作+內建的方法

# =======================>優先掌握的操作:

# 1、按索引取值(正向取+反向取) :只能取

s = "hello world"

# print(s[0],type(s[0])) # "h"

# print(s[-1])

# s[1] = "E" # 不能修改

# 非法操作

# s[2222]

# s[11] = "A"

# 2、切片(顧頭不顧尾,步長)=>屬於拷貝操作

s = "hello world"

# new_s=s[1:7]

# print(new_s)

# print(s)

# new_s=s[1:7:2] #1 3 5

# print(new_s)

# print(s)

# new_s=s[:7:2]

# new_s=s[::2] # 0 2 4 6 8 10

# h l o w r d

# print(new_s)

# new_s=s[::] # 完整拷貝字串,只留一個冒號就可以new_s=s[:]

# print(new_s)


# 3、長度len

# s = "hello world"

# print(len(s))

# res=print("sfd")

# print(res)

# 4、成員運算in和not in

# s = "hello world"

# # print("hel" in s)

# print("egon" not in s) # 語義明確,推薦使用

# # print(not "egon" in s)

# 5、移除空白strip

# s = " \n hel lo \t "

# new_s = s.strip()

# print(new_s)

# print(s) # 沒有改變原字串

# 應用案列:

# name = input("your name>>> ").strip() # name = "egon "

# pwd = input("your pwd>>> ").strip()

#

# if name == "egon" and pwd == "123":

# print('login successful')

# else:

# print('user or password error')


# 去除左右兩邊的非空白字元

# print("**+=-%^#****he**llo**%^#**+=**".strip("*+=-%^#"))

# 6、切分split:把字串按照某個分隔符切成一個列表

# userinfo = "egon_dsb:123:18:3.1"

# res = userinfo.split(":")

# # print(res[0])

# print(res)

# print("-".join(res))

# 純字串組成的列表

# l = ["aaaa", "bbb", "ccc"]

#

# # res=l[0]+":"+l[1]+":"+l[2]

# res = ":".join(l)

# print(res, type(res))

# 7、迴圈

# for i in "hello":

# print(i)


# =======================>需要掌握的操作:

# 1、strip,lstrip,rstrip

# print("***hello***".strip("*"))

# print("***hello***".lstrip("*"))

# print("***hello***".rstrip("*"))

# 2、lower,upper

# msg = "AbCDEFGhigklmn"

# res = msg.lower()

# res = msg.upper()

# print(res)

# res=msg.swapcase()

# print(res)

# 3、startswith,endswith

# msg = "sb is lxx sb"

# print(msg.startswith("sb"))

# print(msg.endswith("b"))

# print(msg.endswith("c"))

# 5、split,rsplit

# userinfo="egon:123:18"

# # print(userinfo.split(":"))

# print(userinfo.split(":",1))

# print(userinfo.rsplit(":",1))

# 6、join

# 7、replace

msg = "***egon hello***"

# res=msg.replace('*','').replace(' ','')

# res=msg.strip('*').replace(' ','')

# print(res)

# s="lxx hahah wocale lxx sb 666"

# # res=s.replace('lxx','sb')

# res=s.replace('lxx','sb',1)

# print(res)

# print(s)

# 4、format的三種玩法

# 4.1 %s的方式

# name = "egon"

# age = 18

# res1="my name is %s my age is %s" % (name,age)

# print(res1)

# 4.2 format的方式

# name = "egon"

# age = 18

# res1="my name is {} my age is {}".format(name,age)

# res1="{0}{0}{0}{1}".format(name,age)

# res1="my name is {name} my age is {age}".format(age=18,name="egon")

# print(res1)

# 4.3 f.txt''

# name = "egon"

# age = 18

# res1 = f.txt"my name is {name} my age is {age}"

# print(res1)


# 瞭解:f搭配{}可以執行字串中的程式碼

# res=f.txt'{len("hello")}'

# print(res)

# f.txt'{print("hello")}'

# f包含的字串可以放到多行

# name = "egon"

# age = 18

# res1 = f.txt"my name is {name} " \

# f.txt"my age is {age}"

# {}內不能有\以及#

# print(f.txt'my name is {{egon}}')

# print('勝率是 %s%%' %70)

# 瞭解:https://zhuanlan.zhihu.com/p/110406030

# 8、isdigit:判斷字串是否由純數字組成

# print("adsf123".isdigit())

# print("123".isdigit())

# print("12.3".isdigit())

age = input('>>>: ') # age = " 18 "
if age.isdigit():
age=int(age)
if age > 18:
print('猜大了')
elif age < 18:
print('猜小了')
else:
print('猜對了')
else:
print('必須輸入數字,小垃圾')

# =======================>瞭解的操作:


# ======================================該型別總結====================================

# 存一個值or存多個值

# 有序or無序

# 可變or不可變(1、可變:值變,id不變。可變==不可hash 2、不可變:值變,id就變。不可變==可hash)

#1、find,rfind,index,rindex,count(字串內建方法)

# x = "hello egon egon egon"

# res=x.find("egon")

# res=x.find("egon123") # -1代表沒有找到

# print(res)

# res=x.rfind("egon")

# print(res)

# res=x.find("egon",0,3)

# print(res)


# res = x.index("egon123") # 找不到則報錯

# print(res)



#2、center,ljust,rjust,zfill

# x = "egon"

# res=x.center(50,'*')

# print(res)

# print(x.ljust(50,"*"))

# print(x.rjust(50,"*"))

# print(x.zfill(50))

# print(x.rjust(50,"0"))

#3、expandtabs

# print("hello\tworld".expandtabs(1))

#4、captalize,swapcase,title

# print("hello world egon".capitalize())

# print("aBcDeF".swapcase())

# print("hello world egon".title())


#5、is其他

# name='egon123'

# print(name.isalnum()) #字串由字母或數字組成

# print(name.isalpha()) #字串只由字母組成

#

# name="aaainputbbbbb"

# print(name.isidentifier())

# name="abc123"

# print(name.islower())

# print(name.isupper())

# name=" "

# print(name.isspace())

# name="My Name Is Egon"

# print(name.istitle())

#6、is數字系列
#在python3中
num1=b'4' #bytes
num2=u'4' #unicode,python3中無需加u就是unicode
num3='四' #中文數字
num4='Ⅳ' #羅馬數字

#1、 bytes、unicode

# print(num1.isdigit())

# print(num2.isdigit())

# print(num3.isdigit())

# print(num4.isdigit())


# 2、unicode、中文數字、羅馬數字

# print(num2.isnumeric())

# print(num3.isnumeric())

# print(num4.isnumeric())

# 3、unicode

# print(num2.isdecimal())

# print(num3.isdecimal())

# print(num4.isdecimal())


# ======================================該型別總結====================================

# 存一個值

# 有序

# 不可變

# x="hello"

# x[0]="H"

CCC列表型別

# ======================================基本使用======================================

# 1、用途:按照索引存放多個任意型別的值,索引反映的是位置/順序

# 2、定義方式:在[]內用逗號分割開多個任意型別的元素

# l=[111,1.1,"aaa",[2222,3333]] # l=list([111,1.1,"aaa",[2222,3333]])

# print(type(l))

# 資料型別轉換

# res=list("hello")

# res=list({"k1":1,"k2":2,"k3":3})

# print(res)

# 3、常用操作+內建的方法

# ===============3.1 優先掌握的操作:

#1、按索引存取值(正向存取+反向存取):即可以取可以改值,不能加值
l1 = [11,22,33,44,55]

# print(l1[0])

# print(l1[10])

# print(l1[-1])

# print(id(l1))

# l1[0] = 100

# print(id(l1))

# l1[5] = 11111

# d = {'k1':2}

# d['kkkk']=22222

# print(d)

#2、切片(顧頭不顧尾,步長)
l1 = [11,22,[66,77]]

# res=l1[2:4]

# print(res)

# print(l1)

# 2.1 淺copy:

# l2=l1[:]

# l2=l1.copy()

#

# print(id(l1[0]),id(l1[1]),id(l1[2]))

# print(id(l2[0]),id(l2[1]),id(l2[2]))




# l1[0] = "aaa"

# l1[1] = "bbb"

# l1[2] = "ccc"

# l1[2][0] = 8888

# print(l2)


# from copy import deepcopy

# l3=deepcopy(l1)

# print(id(l3[0]),id(l3[1]),id(l3[2]))

#

# l1[2][0]=6666

# print(l1)

# print(l3)

# 示範1:

# l1[0]=1000

# print(l1)

# print(l2)

# 示範2:

# l1[-1][0]=666

# print(l1)

# print(l2)

# 瞭解:

# res=l1[-1:-4:-1]

# res=l1[::-1]

# print(res)


#3、長度

# l1 = [11,22,[66,77]]

# print(len(l1))

#4、成員運算in和not in

# l1 = [111,22,[66,77]]

# print([66,77] in l1)

# print(66 in l1)

# print(66 not in l1)

#5、追加
l1=[11,222]

# l1.append(33)

# l1.append(44)

# l1.append([55,66])

# print(l1)

# l1.insert(1,"aaa")

# print(l1)

#6、刪除
l1=[11,222,[1,2]]
#6.1 萬能刪除,沒有返回值,代表的是單純的刪除

# del l1[0]

# print(l1)

#6.2 指定元素刪除,沒有返回值,代表的是單純的刪除

# res=l1.remove([1,2])

# print(l1)

# print(res)

#6.3 指定索引刪除,有返回值,代表的是取走操作

# res=l1.pop(1)

# print(l1)

# print(res)

#7、迴圈

# l1=[11,222,[1,2]]

# for x in l1:

# print(x)


# ===============3.2 需要掌握的操作:

l1=[11,22,333,333,333,]

# l1.clear()

# print(l1)

# print(l1.count(333333333))

# l2=[444,555]

# for item in l2:

# # l1.append(item)

# l1.extend(l2)

l1.extend("hello")
print(l1)

# l1=[11,22,333,333,333,]

# res=l1.index(333,0,2)

# res=l1.index(444)

# print(res)

# l1=[11,22,"aaa",'bbb']

# l1.reverse()

# l1=l1[::-1]

# print(l1)

# l1 = [11, 22, "aaa", 'bbb']

# l1 = [-3,99,12,-5,93]

# l1.sort(reverse=True)

# print(l1)

# ======================================該型別總結====================================

# 存一個值or存多個值

# 有序or無序

可變or不可變(1、可變:值變,id不變。可變==不可hash 2、不可變:值變,id就變。不可變==可hash)

ddd 元組型別

# 什麼是元組?

# 元組就是一個不可變的列表

#

# ======================================基本使用======================================

# 1、用途: 按照索引存放多個任意型別的值,索引反應的是位置/順序

# 2、定義方式:在()內用逗號分隔開多個任意類下的值/元素

# t=(10)

# print(type(t))

# 強調:當元組內只有一個元素時,必須加逗號

# t=(10,)

# print(type(t))

# t=(10,1.1,"aaa",[11,22])

# print(t[-1][0])

# t[0]=11111

# t[-1]=333333

# t=(11,22,[33,44])

# print(id(t[0]),id(t[1]),id(t[2]))

#

# t[2][0]=333333333

# # print(t)

# print(id(t[0]),id(t[1]),id(t[2]))

# t=(11,22) # t=tuple(...)

# print(type(t))

# 型別轉換

# tuple(所有可以被for迴圈遍歷的型別)

# t=()

# print(t)

# print(type(t))

# 3、常用操作+內建的方法

#優先掌握的操作:
#1、按索引取值(正向取+反向取):只能取

# t=(10,1.1,"aaa",[11,22])

# print(t[0])

#2、切片(顧頭不顧尾,步長)

# t=(11,22,33,44,55)

# print(t[0:3])

#3、長度

# t=(11,22,33,44,55)

# print(len(t))

#4、成員運算in和not in

# t=(11,22,33,44,55)

# print(11 in t)

#5、迴圈

# for x in t:

# print(x)


#需要掌握的操作:

# t=(11,22,33,44,55)

# ======================================該型別總結====================================

# 存多個值

# 有序

不可變(1、可變:值變,id不變。可變==不可hash 2、不可變:值變,id就變。不可變==可hash)

eee 字典型別

# ======================================基本使用======================================

# 1、用途:按key:value的形式存放多個任意型別的value,key反映的是value的屬性

# 2、定義方式:在{}內用逗號分隔開多個key:value,其中value可以是任意型別

# 而key必須是不可變的型別,通常是字串型別

# d={'k1':111,'k1':222,'k1':3333} # key重複,只保留一個

# print(d)


# d={1:"aaa",3.1:'bbbb',[1,2]:"ccc"}

# d={1:"aaa",3.1:'bbbb',():"ccc"} # d=dict(...)

# print(type(d))

# print(d[()])

# 型別轉換

# l=[("name","egon"),("age",18),["gender","male"]]

# res=dict(l)

# print(res)

# d=dict(x=1,y=2,z=3)

# print(d)

# 空字典

# d={}

# print(type(d))

# dic={}.fromkeys(["name",'age',"gender"],None)

# dic={}.fromkeys("hello",None)

# print(dic)


# 3、常用操作+內建的方法

#==========>優先掌握的操作:
#1、按key存取值:可存可取

# d={'k1':111}

# print(d['k1'])

# d['k2']=222

# print(d)

#2、長度len

# d={'k1':111,'k2':222}

# print(len(d))


#3、成員運算in和not in

# d={'k1':111,'k2':222}

# print('k1' in d)

# print(111 in d)


#4、刪除
d={'k1':111,'k2':222}
#6.1 萬能刪除,沒有返回值,代表的是單純的刪除

# del d['k1']

# print(d)

#6.2 隨機刪,返回一個元組

# res=d.popitem()

# print(d)

# print(res)

#6.3 指定key刪除,有返回值,代表的是取走操作

# res=d.pop('k1')

# print(d)

# print(res)

#5、鍵keys(),值values(),鍵值對items()
"""

>>> d={'k1':111,'k2':222}
>>> d.keys()
>>> ['k2', 'k1']
>>> d.values()
>>> [222, 111]
>>> d.items()
>>> [('k2', 222), ('k1', 111)]
>>> """

#6、迴圈

# d={'k1':111,'k2':222}

# for k in d:

# print(k)

# for v in d.values():

# print(v)

# for k,v in d.items():

# print(k,v)

# keys=[]

# for k in d:

# keys.append(k)

keys=list(d.keys())
print(keys)

# ======================================該型別總結====================================

# 存一個值or存多個值

# 有序or無序

# 可變or不可變(1、可變:值變,id不變。可變==不可hash 2、不可變:值變,id就變。不可變==可hash)

fff 集合及一些補充知識

# t = (1)

# print(t,type(t))

# """

# 推薦你們在使用容器型別的元素的時候

# 如果該容器型別只有一個元素 那麼你也習慣性的

# 將逗號加上

# t = (1,)

# l = ['jason',]

# """

# d = dict(username='jason', age=18)

# print(d) # {'username': 'jason', 'age': 18}

# 型別轉換

# d1 = dict([['username','password'],('jason',123)])

# print(d1) # {'username': 'password', 'jason': 123}

# 操作方法

# 取值

"""
字典預設暴露給外界的可操作的只有字典的key
字典是無需的 根本沒有索引一說

程式設計師第一準則
能少寫一個字母絕對不多寫一個
"""
d = {'username': 'jason', 'password': 123}

# print(d['username']) # 不推薦使用該方法

# print(d['xxx']) # KeyError: 'xxx'

# 1 get方法

# res = d.get('username')

# print(res) # jason

# res = d.get('xxx')

# print(res) # None 鍵不存在會返回None 不會報錯

# res = d.get('username', '你搞什麼飛機 這個鍵不存在 去你妹啊')

# print(res) # 鍵存在還是返回對應的值

# res = d.get('xxx', '你搞什麼飛機 這個鍵不存在 去你妹啊')

# print(res) # 鍵不存在 返回get方法裡面第二個引數

# 字典新增鍵值對

# 方式1

# d['hobby'] = 'study' # 字典的key不存在新增

# print(d)

# d['username'] = 'egon'

# print(d) # 字典的key存在則修改

# 方式2

# d.update(username='jason')

# print(d) # 特點同上

# 方式3

"""
鍵如果存在的情況下 那麼不做修改 而是將對應的value取出
鍵如果不存在的情況下 那麼就是新增
"""

# d.setdefault('xxx',123)

# print(d) # 鍵不存在是新增

# res = d.setdefault('username',123)

# print(d) # {'username': 'jason', 'password': 123}

# print(res) # jason

# 快速構造字典

# res = {}.fromkeys(['k1','k2','k3'],[])

# # print(res) # {'k1': [], 'k2': [], 'k3': []}

# res.get('k1').append(123)

# print(res)

"""
A
{'k1': [123], 'k2': [], 'k3': []}
B
{'k1': [123], 'k2': [123], 'k3': [123]}
C
報錯
D
我TMD的也不知道
"""

# 彈出

# res = d.pop('username') # 將括號內指定的key對應的value彈出

# print(d,res) # jason

# res1 = d.popitem() # 將彈出的鍵值對組織成元組的形式返回出去

# print(d,res1) # {'username': 'jason'} ('password', 123)


# 字典方法三劍客

# print(d.keys()) # 獲取字典所有的key

# print(d.values()) # 獲取字典所有的value

# print(d.items()) # 獲取字典所有的key和value組織成小元組

"""
可以直接只看裡面的資料結構
dict_keys(['username', 'password'])
dict_values(['jason', 123])
dict_items([('username', 'jason'), ('password', 123)])
"""

# for key in d.keys():

# print(key)

# for value in d.values():

# print(value)

# for item in d.items():

# print(item)

# for k, v in d.items():

# print(k,v)

# 清空

# d.clear()

# print(d)

# __class__ # 雙下class

# s = {1,2,3,4,5,6,7,8}

# print(type(s))

# s1 = {}

# d1 = {}

# print(type(s1),type(d1)) # <class 'dict'> <class 'dict'>

# # 定義空集合一定要用set關鍵字

# ss = set()

# print(ss,type(ss)) # set() <class 'set'>


# s = {1,1,1,2,3,3,4,3,2,3,4,6,5,3,}

# print(s)

# 型別轉換

# s1 = set('egon is o DSB')

# print(s1)

# s2 = set([1,2,3,4,5,6,7,7,7,7,7])

# print(s2)

# s3 = set({'username':'jason','password':123})

# print(s3) # {'password', 'username'}

l = [4,3,2,3,4,6,7,8,1,2,3]

# # 先轉成集合

# s = set(l)

# # 再轉成列表

# l1 = list(s)

# print(l1)

# new_l = []

# for i in l:

# if i not in new_l:

# new_l.append(i)

# print(new_l)


# 使用者1的好友列表

friends1 = {'jason','tank','tony','jerry'}

# 使用者2的好友列表

friends2 = {'jason','tony','owen','oscar'}

# 1 求兩個使用者的共同好友 交集

# res = friends1 & friends2

# print(res) # {'jason', 'tony'}

# 2 求兩個使用者所有的好友

# res = friends1 | friends2

# print(res) # {'jerry', 'jason', 'oscar', 'tony', 'tank', 'owen'}

# 3 求使用者1獨有的好友

# res1 = friends1 - friends2

# res2 = friends2 - friends1

# print(res1,res2) # {'jerry', 'tank'} {'owen', 'oscar'}

# 4 求兩個使用者各自獨有的好友 對稱差集

# res = friends1 ^ friends2

# print(res) # {'owen', 'jerry', 'tank', 'oscar'}

# 5 子集 父集

s1 = {12,3,4,5,6}
s2 = {12,6}
print(s1 > s2) # s1是否是s2的父集
print(s2 < s1) # s2是否是s1的子集