更多列表的使用方法和API,請參考Python文檔:/tupian/20230522/functions.html
append:用于在列表末尾追加新對象:
# append函數(shù)
lst = [1,2,3]
lst.append(4)
# 輸出:[1, 2, 3, 4]
print lst
復(fù)制代碼
count:用于統(tǒng)計(jì)某個元素在列表中出現(xiàn)的次數(shù):
# count函數(shù)
temp_str = ['to','be','not','to','be']
# 輸出:2
print temp_str.count('to')
extend:可以在列表末尾一次性追加另一個序列中的多個值,和連接操作不同,extend方法是修改了被擴(kuò)展的序列(調(diào)用extend方法的序列),而原始的連接操作返回的是一個全新的列表
# extend函數(shù)
a = [1,2,3]
b = [4,5,6]
a.extend(b)
#輸出:[1, 2, 3, 4, 5, 6]
print a
# 輸出:[1, 2, 3, 4, 5, 6, 7, 8, 9]
print a + [7,8,9]
# 輸出:[1, 2, 3, 4, 5, 6]
print a
index:用于從列表中找出某個值第一個匹配項(xiàng)的索引位置
# index函數(shù)
knights = ['we','are','the','knights','who','say','ni']
# 輸出:4
print knights.index('who')
# 拋出異常:ValueError: 'me' is not in list
print knights.index('me')
insert:用于將對象插入到列表中
# insert函數(shù)
numbers = [1,2,3,5,6]
numbers.insert(3,'four')
# 輸出:[1, 2, 3, 'four', 5, 6]
print numbers
pop:移除列表中的一個元素(默認(rèn)是最后一個),并且返回該元素的值。通過pop方法可以實(shí)現(xiàn)一種常見的數(shù)據(jù)結(jié)構(gòu)——棧(LIFO,后進(jìn)先出)。
# pop函數(shù)
x = [1,2,3]
x.pop()
# 輸出:[1, 2]
print x
y = x.pop(0)
# 輸出:[2]
print x
# 輸出:1
print y
remove:移除列表中某個值的第一個匹配項(xiàng)
# remove函數(shù)
x = ['to','be','not','to','be']
x.remove('to')
# 輸出:['be', 'not', 'to', 'be']
print x
# 移除列表沒有的元素會拋出異常
x.remove('too')
reverse:將列表中的元素反向存放
# reverse函數(shù)
x = [1,2,3]
x.reverse()
# 輸出:[3, 2, 1]
print x
sort:對列表進(jìn)行排序。注意:sort函數(shù)時沒有返回值的(None),它作用于源序列??梢酝ㄟ^sorted函數(shù)來獲取已排序的列表副本。
# sort函數(shù)
x = [3,1,2,7,6,9,5,4,8]
y = x[:]
z = x
y.sort()
# 輸出:[3, 1, 2, 7, 6, 9, 5, 4, 8]
print x
# 輸出:[1, 2, 3, 4, 5, 6, 7, 8, 9]
print y
# 輸出:[3, 1, 2, 7, 6, 9, 5, 4, 8]
print z
當(dāng)前標(biāo)題:python之列表常用方法-創(chuàng)新互聯(lián)
文章源于:http://chinadenli.net/article40/diceeo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供手機(jī)網(wǎng)站建設(shè)、外貿(mào)建站、微信小程序、品牌網(wǎng)站制作、定制網(wǎng)站、網(wǎng)站內(nèi)鏈
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)