python常見數據類型及操作方法
title: “python數據類型及其常用方法”
date: 2020-04-21T10:15:44+08:00
可變數據類型:允許變數的值發生變化,即如果對變數進行append、+=等這種操作後,只是改變了變數的值,而不會新建一個對象,變數引用的對象的地址也不會變化,不過對於相同的值的不同對象,在記憶體中則會存在不同的對象,即每個對象都有自己的地址,相當於記憶體中對於同值的對象保存了多份,這裡不存在引用計數,是實實在在的對象.如 **list,dict,set **
不可變數據類型:不允許變數的值發生變化,如果改變了變數的值,相當於是新建了一個對象,而對於相同的值的對象,在記憶體中則只有一個對象,內部會有一個引用計數來記錄有多少個變數引用這個對象。如 **Number,String, Tuple **
list常用方法
增
append()
# append用於在列表末尾追加新的對象
# list.append(obj)
a = [1,2,3]
print(a.append('4'))
# the result : [1, 2, 3, '4']
extend()
# extend方法可以在列表的末尾一次性追加另一個序列中的多個值
a = [1,2,3]
b = [4,5,6]
a.extend(b)
print(a)
# the result :[1, 2, 3, 4, 5, 6]
insert()
# insert方法用於將對象插入到列表中
# list.insert(index, obj)
a = [1,2,3]
a.insert(0,'aa')
print(a)
# the result : ['aa', 1, 2, 3]
刪
pop()
# pop方法會移除列表中的一個元素(默認是最後一個),並且(返回)該元素的值,若索引溢出會報錯
# list.pop([index=-1])
a = [1,2,3]
print(a.pop())
# the result : 3
print(a)
# the result : [1,2]
remove()
# remove方法用於移除列表中某個值的第一個匹配項
a = ['aa','bb','cc','aa']
a.remove('aa')
print(a)
# the result : ['bb', 'cc', 'aa']
改
reverse()
# reverse方法將列表中的元素反向存放
a = ['a','b','c']
a.reverse()
print(a)
# the result : ['c', 'b', 'a']
sort()
# sort方法用於在原位置對列表進行排序,意味著改變原來的列表,讓其中的元素按一定順序排列
# list.sort(cmp=None, key=None, reverse=False)
# cmp -- 可選參數, 如果指定了該參數會使用該參數的方法進行排序。
# key -- 主要是用來進行比較的元素,只有一個參數,具體的函數的參數就是取自於可迭代對象中,指定可迭代對 象中的一個元素來進行排序。
# reverse -- 排序規則,reverse = True 降序, reverse = False 升序(默認)。
def takeSecond(elem):
return elem[1]
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
random.sort(key=takeSecond,reverse=True)
print (random)
# the result : [(3, 4), (1, 3), (2, 2), (4, 1)]
查
count()
# count方法統計某個元素在列表中出現的次數
a = ['aa','bb','cc','aa','aa']
print(a.count('aa'))
# the result : 3
index()
# index函數用於從列表中找出某個值第一個匹配項的索引位置,匹配範圍內沒有則報錯,需要注意的是end值為左閉右開區間
# list.index(x[, start[, end]])
a = [1,2,3,1]
print(a.index(1))
print(a.index(3,1,3))
# the result : 0
# the result : 2
enumerate()
# 帶索引的遍歷
# enumerate(sequence, [start=0])
# sequence -- 一個序列、迭代器或其他可迭代對象。
# start -- 下標起始位置,可選參數,默認為0。
li = [11,22,33]
for k,v in enumerate(li):
print(k,v)
# 0 11
# 1 22
# 2 33
print(list(enumerate(li,8)))
#[(8, 11), (9, 22), (10, 33)]
Dict常用方法
增
fromkeys()
#dict.fromkeys(seq[, value])
seq = ('Google', 'Runoob', 'Taobao')
dict = dict.fromkeys(seq,1)
print(dict)
# {'Google': 1, 'Runoob': 1, 'Taobao': 1}
zip()
# 將兩個列表組合成字典
keys = ['a', 'b']
values = [1, 2]
print(dict(zip(keys,values)))
# {'a': 1, 'b': 2}
相反,zip()作用於字典,會創建一個**只能訪問一次的迭代器 **
可以思考–怎樣在數據字典中執行一些計算操作(比如求最小值、最大值、排序等等)?
#考慮下面的股票名和價格映射字典:
prices = {'ACME': 45.23,'AAPL': 612.78,'IBM': 205.55,'HPQ': 37.20,'FB': 10.75}
#為了對字典值執行計算操作,通常需要使用zip()函數先將鍵和值反轉過來.
#下面是查找最小和最大股票價格和股票值的程式碼:
min_price = min(zip(prices.values(), prices.keys()))
# min_price is (10.75, 'FB')
max_price = max(zip(prices.values(), prices.keys()))
# max_price is (612.78, 'AAPL')
#類似的,可以使用zip() 和sorted() 函數來排列字典數據:
prices_sorted = sorted(zip(prices.values(), prices.keys()))
# prices_sorted is [(10.75, 'FB'), (37.2, 'HPQ'),(45.23, 'ACME'), (205.55, 'IBM'),(612.78, 'AAPL')]
執行這些計算的時候,需要注意的是zip() 函數創建的是一個只能訪問一次的迭代器。比如,下面的程式碼就會產生錯誤:
prices_and_names = zip(prices.values(), prices.keys())
print(min(prices_and_names)) # OK
print(max(prices_and_names)) # ValueError: max() arg is an empty sequence
#字典值相同,鍵不同,比較值的大小
prices = { 'AAA' : 45.23, 'ZZZ': 45.23 }
min(zip(prices.values(), prices.keys()))
#(45.23, 'AAA')
max(zip(prices.values(), prices.keys()))
#(45.23, 'ZZZ')
刪
clear()
# clear方法清除字典中所有的項,這是一個原地操作,所以無返回值(或則說返回None)
d = {'name':"tom"}
d.clear()
print(d)
#the result : {}
改
pop()
# 刪除字典給定鍵 key 及對應的值,返回值為被刪除的值
d = {'Tom':8777,'Jack':8888,'Fly':6666}
v = d.pop('Tom')
print(v)
# 8777
print(d)
# {'Jack': 8888, 'Fly': 6666}
update()
# update方法可以利用一個字典項更新另一個字典,提供的字典中的項會被添加到舊的字典中,如有相同的鍵則會被覆蓋
d = {'Tom':8777,'Jack':8888,'Fly':6666}
a = {'Tom':110,'Test':119}
d.update(a)
print(d)
#the result :{'Fly': 6666, 'Test': 119, 'Jack': 8888, 'Tom': 110}
查
get()
# get方法是個更寬鬆的訪問字典的方法,如果試圖訪問字典中不存在的項時不會報錯,僅會返回:None
d = {'Tom':8777,'Jack':8888,'Fly':6666}
print(d.get('Tom'))
#the result :8777
print(d.get('not_exist'))
#the result:None
item()
# dict.items()返回可遍歷的(鍵, 值) 元組數組。
dict = {'Google': 'www.google.com', 'Runoob': 'www.runoob.com'}
print (dict.items())
# dict_items([('Google', 'www.google.com'), ('Runoob', 'www.runoob.com')])
由此引出遍歷字典的三種方法
for k,v in d.items():
print(k,v)
for k in d.values():
print(k)
for k in d.keys():
print(k)
set常用方法
list_1 = [1,2,3,4,5,1,2]
list_2 = [4,5,6,7,8]
去重
print(set(list_1))
# {1, 2, 3, 4, 5}
print(list_1)
# [1, 2, 3, 4, 5, 1, 2]
交集
print(set(list_1).intersection(set(list_2)))
# {4, 5}
並集
print(set(list_1).union(set(list_2)))
# {1, 2, 3, 4, 5, 6, 7, 8}
差集
# 在list_1中有在list_2中沒有
print(set(list_1).difference(set(list_2)))
# {1, 2, 3}
str常用方法(不可變)
find(),rfind()
# find方法可以在一個較長的字元串中查找子串,他返回子串所在位置的最左端索引,如果沒有找到則返回-1
a = 'abcdefghijk'
print(a.find('abc'))
#the result : 0
print(a.find('abc',10,100))
#the result : -1 指定查找的起始和結束查找位置
# rfind方法類似,是從後往前找
join()
# 返回一個字元串,是split方法的逆方法,用來連接序列中的元素,並且需要被連接的元素都必須是字元串。
a = ['1','2','3']
print('+'.join(a))
#the result : 1+2+3
split()
# split是join的逆方法,用來將字元串分割成序列
print('1+2+3+4'.split('+'))
#the result : ['1', '2', '3', '4']
strip()
# strip 方法返回去除首位空格(不包括內部)的字元串
print(" test test ".strip())
#the result :「test test」
replace()
# replace方法返回某字元串所有匹配項均被替換之後得到字元串
print("This is a test".replace('is','is_test'))
#the result : This_test is_test a test