Python使用list一、list
Python內(nèi)置的一種數(shù)據(jù)類型是列表:list。list是一種有序的集合,可以隨時添加和刪除其中的元素。
比如,列出班里所有同學(xué)的名字,就可以用一個list表示:
classmates = ['Michael', 'Bob', 'Tracy']print(classmates)
變量classmates就是一個list。
len()函數(shù)1. 獲得list元素的個數(shù):classmates = ['Michael', 'Bob', 'Tracy']print(len(classmates))
用索引來訪問list中每一個位置的元素,記得索引是從0開始的:
classmates = ['Michael', 'Bob', 'Tracy']
print(classmates[0])
print(classmates[1])
print(classmates[2])
print(classmates[3])
當(dāng)索引超出了范圍時,Python會報一個IndexError錯誤,所以,要確保索引不要越界,記得最后一個元素的索引是len(classmates) - 1。
如果要取最后一個元素,除了計算索引位置外,還可以用-1做索引,直接獲取最后一個元素:
print(classmates[-1])
以此類推,可以獲取倒數(shù)第2個、倒數(shù)第3個:
classmates = ['Michael', 'Bob', 'Tracy']
print(classmates[-1])
print(classmates[-2])
print(classmates[-3])
print(classmates[-4])
當(dāng)然,倒數(shù)第4個就越界了。
2. list是一個可變的有序表,往list中追加元素到末尾:classmates = ['Michael', 'Bob', 'Tracy']
classmates.a(chǎn)ppend('Adam')
print(classmates)
也可以把元素插入到指定的位置,比如索引號為1的位置:
classmates = ['Michael', 'Bob', 'Tracy']#替換classmates.insert(1, 'Jack')
print(classmates)
pop()函數(shù)1. 刪除list末尾的元素classmates = ['Michael', 'Bob', 'Tracy']
print(classmates.pop())
print( classmates)['Michael', 'Jack', 'Bob', 'Tracy']
2. 刪除指定位置的元素,用pop(i)方法,其中i是索引位置。
classmates.pop(1)
print(classmates)
3. 把某個元素替換成別的元素,可以直接賦值給對應(yīng)的索引位置:
classmates = ['Michael', 'Bob', 'Tracy']
classmates[1] = 'Sarah'
print(classmates)
list里面的元素的數(shù)據(jù)類型也可以不同,比如:
L = ['Apple', 123, True]
list元素也可以是另一個list,比如:
s = ['python', 'java', ['asp', 'php'], 'scheme']print(len(s))
要注意s只有4個元素,其中s[2]又是一個list,如果拆開寫就更容易理解了:
p = ['asp', 'php']s = ['python', 'java', p, 'scheme']
要拿到'php'可以寫p[1]或者s[2][1],因此s可以看成是一個二維數(shù)組,類似的還有三維、四維……數(shù)組,不過很少用到。
如果一個list中一個元素也沒有,就是一個空的list,它的長度為0:
L = []len(L)二、總結(jié)
本文基于Python基礎(chǔ),主要介紹了Python基礎(chǔ)中l(wèi)ist列表,通過list列表的兩個函數(shù) ,對list的語法做了詳細(xì)的講解,用豐富的案例 ,代碼效果圖的展示幫助大家更好理解 。
使用Python編程語言,方便大家更好理解,希望對大家的學(xué)習(xí)有幫助。
-
可編程邏輯
+關(guān)注
關(guān)注
7文章
524瀏覽量
44582 -
python
+關(guān)注
關(guān)注
56文章
4825瀏覽量
86223
發(fā)布評論請先 登錄
創(chuàng)建列表 (List) 介紹,一起來看看是做什么的
Demo示例: List的使用
Ansible Playbook中的變量使用技巧
Python中的迭代器與生成器
不同類型adc的優(yōu)缺點分析
對比Python與Java編程語言
圖紙模板中的文本變量

如何在文本字段中使用上標(biāo)、下標(biāo)及變量

Linux環(huán)境變量配置方法
使用Python搭建簡易本地http服務(wù)器,升級WIPI模組

pytorch和python的關(guān)系是什么
技術(shù)干貨驛站 ▏深入理解C語言:基本數(shù)據(jù)類型和變量

評論