list
生成list
names = ['park','json','xff','ycq']
names = []
spam = [['cat', 'bat'], [10, 20, 30, 40, 50]] #就像其他語言里的多維數(shù)組
獲取list元素
names[0]
spam[1][4]
names[-1]
切片
names[:] #復(fù)制list
names[2:5]
names[:5]
name[3:-1]
len()函數(shù)
獲取對(duì)象的長(zhǎng)度,可用于str、list、dict
list連接和復(fù)制
根str的連接和復(fù)制一樣
[1, 2, 3] + ['A', 'B', 'C']
['X', 'Y', 'Z'] * 3
del語句
需要知道要?jiǎng)h除元素的下標(biāo)??捎糜趕tr、list、dict、int、float
del names[2]
list循環(huán)
supplies = ['pens', 'staplers', 'flame-throwers', 'binders']
for i in range(len(supplies)):
print( supplies[i])
這個(gè)用法感覺有點(diǎn)像c語言
supplies = ['pens', 'staplers', 'flame-throwers', 'binders']
for i in supplies:
print(i)
這樣才像Python
in 和 not in
驗(yàn)證成全資格,可用于if的條件判斷
list的方法
index()
返回元素的下標(biāo)
spam = ['hello', 'hi', 'howdy', 'heyas']
spam.index('hello')
append() / insert(,)
list添加元素,沒有返回值
spam.append('moose')
添加元素到list末尾
spam.insert(1, 'chicken')
添加元素后’chicken‘在位置1
pop() / pop(9)
list.pop()
刪掉list的最后一個(gè)元素
list.pop(9)
刪掉list下標(biāo)為9的元素
有返回值的list方法
remove()
根據(jù)’元素值‘刪除元素,永久刪除。無返回值
spam.remove('bat')
刪除不存在的元素會(huì)報(bào)錯(cuò)ValueError: list.remove(x): x not in list
所以在刪除前應(yīng)該確定成員資格 if 'xx' in spam
sort()排序
永久排序,
spam.sort()
spam.sort(reverse=True)
sort()方法對(duì)字符串排序時(shí),使用“ASCII 字符順序”,而不是實(shí)際的字
典順序。這意味著大寫字母排在小寫字母之前
spam.sort(key=str.lower)
需要按照普通的字典順序來排序,就在sort()方法調(diào)用時(shí),將關(guān)鍵字參數(shù)
key 設(shè)置為str.lower。
不可變數(shù)據(jù)類型的改變
不可變數(shù)據(jù)類型:數(shù)子、字符串、布爾
可變數(shù)據(jù)類型:list、Dict、
可以通過id()函數(shù)來看類型是不是可變數(shù)據(jù)類型,給變量重新賦值后如果ID改變那么就是不可變數(shù)據(jù)類型??筛淖償?shù)據(jù)類型實(shí)際上指的是python開辟的內(nèi)存區(qū)間的內(nèi)容是可以改變的。
在參數(shù)調(diào)用的時(shí)候,不可變數(shù)據(jù)類型調(diào)用的是值,不可變數(shù)量類型調(diào)用的是指針。
name = 'Zophie a cat'
name[7] = 'the'
str、tuple是不可變的,以上的做法會(huì)報(bào)錯(cuò)TypeError: 'str' object does not support item assignment
但是可以通過一些方法構(gòu)造新的str和tuple
name = 'Zophie a cat'
newName = name[0:7] + 'the' + name[8:12]
tuple1 = (1,2,3,4)不能修改元組中的一個(gè)元素,例如tuple1[0] = 6,會(huì)出錯(cuò)。但是可以這樣做給tuple1重新賦值,tuple1 = (6,2,3,4)
元組
names = ('park','cff','ycq')
names = ('park',)
如果元組中只有一個(gè)值,你可以在括號(hào)內(nèi)該值的后面跟上一個(gè)逗號(hào)
數(shù)據(jù)類型轉(zhuǎn)換
list()和tuple()