1. 程式人生 > >python列表基礎操作

python列表基礎操作

rem tle 我想 pop pri 技術分享 接下來 pan 列表

Python列表基本操作

記住一句話,叫做顧首不顧尾

首先我們來定義一個列表

name = ["jixuege","dajiba","boduoye","cangjinkong","youtianai"]

接下來,我們就對這個列表來進行一系列的操作

1、切片

取值,取第一個和第二個

print(name[0],name[1])
打印結果
jixuege dajiba

說明:

上面的0和1指的是小標,從左到右順序就是從0開始一直到4

打印一個區間

name = ["jixuege","dajiba","boduoye","cangjinkong","youtianai"]

print(name[:2])
打印結果
[‘jixuege‘, ‘dajiba‘]

打印最後一個
name = ["jixuege","dajiba","boduoye","cangjinkong","youtianai"]
print(name[-1])
打印結果
youtianai

2、追加
比如說我想追加一個人進去
技術分享 技術分享
name = ["jixuege","dajiba","boduoye","cangjinkong","youtianai"]
name.append("xiha")
print(name)
打印結果

[‘jixuege‘, ‘xitong‘, ‘dajiba‘, ‘youhua‘, ‘boduoye‘, ‘cangjinkong‘, ‘youtianai‘, ‘xiha‘]
技術分享 技術分享

這個會追加到末尾

還有一種就是插入insert

技術分享 技術分享
name = ["jixuege","dajiba","boduoye","cangjinkong","youtianai"]

name.insert(2,"youhua")
print(name)
打印結果
[‘jixuege‘, ‘dajiba‘, ‘youhua‘, ‘boduoye‘, ‘cangjinkong‘, ‘youtianai‘]
技術分享 技術分享
 

3、修改

直接修改即可

name = ["jixuege","dajiba","boduoye","cangjinkong","youtianai"]
name[2]="wuming"
print(name)
打印結果
[‘jixuege‘, ‘dajiba‘, ‘wuming‘, ‘cangjinkong‘, ‘youtianai‘]

4、刪除

直接清空

name = ["jixuege","dajiba","boduoye","cangjinkong","youtianai"]
name.clear()
print(name)
打印結果
[]
 
刪除指定元素
技術分享 技術分享
name = ["jixuege","dajiba","boduoye","cangjinkong","youtianai"]
name.remove("jixuege")
print(name)
打印結果

[‘dajiba‘, ‘boduoye‘, ‘cangjinkong‘, ‘youtianai‘]
技術分享 技術分享

刪除指定下標

name = ["jixuege","dajiba","boduoye","cangjinkong","youtianai"]
del name[2]
print(name)
打印結果
[‘jixuege‘, ‘dajiba‘, ‘cangjinkong‘, ‘youtianai‘]

不指定下標刪除最後一個
name = ["jixuege","dajiba","boduoye","cangjinkong","youtianai"]
name.pop()
print(name)
打印結果
[‘jixuege‘, ‘dajiba‘, ‘boduoye‘, ‘cangjinkong‘]

指定下標
name = ["jixuege","dajiba","boduoye","cangjinkong","youtianai"]
name.pop(1)
print(name)
打印結果
[‘jixuege‘, ‘boduoye‘, ‘cangjinkong‘, ‘youtianai‘]

python列表基礎操作