python里面的list
python里面的list
list
Python內置的一種數據類型是列表:list。list是一種有序的集合,可以隨時添加和刪除其中的元素。
比如,列出班里所有同學的名字,就可以用一個list表示:
>>> classmates = ['Michael', 'Bob', 'Tracy'] >>> classmates ['Michael', 'Bob', 'Tracy']變量classmates就是一個list。用len()函數可以獲得list元素的個數:
>>> len(classmates) 3用索引來訪問list中每一個位置的元素,記得索引是從0開始的:
>>> classmates[0] 'Michael' >>> classmates[1] 'Bob' >>> classmates[2] 'Tracy' >>> classmates[3] Traceback (most recent call last):File "<stdin>", line 1, in <module> IndexError: list index out of range當索引超出了范圍時,Python會報一個IndexError錯誤,所以,要確保索引不要越界,記得最后一個元素的索引是len(classmates) - 1。
如果要取最后一個元素,除了計算索引位置外,還可以用-1做索引,直接獲取最后一個元素:
>>> classmates[-1] 'Tracy'以此類推,可以獲取倒數第2個、倒數第3個:
>>> classmates[-2] 'Bob' >>> classmates[-3] 'Michael' >>> classmates[-4] Traceback (most recent call last):File "<stdin>", line 1, in <module> IndexError: list index out of range當然,倒數第4個就越界了。
list是一個可變的有序表,所以,可以往list中追加元素到末尾:
>>> classmates.append('Adam') >>> classmates ['Michael', 'Bob', 'Tracy', 'Adam']也可以把元素插入到指定的位置,比如索引號為1的位置:
>>> classmates.insert(1, 'Jack') >>> classmates ['Michael', 'Jack', 'Bob', 'Tracy', 'Adam']要刪除list末尾的元素,用pop()方法:
>>> classmates.pop() 'Adam' >>> classmates ['Michael', 'Jack', 'Bob', 'Tracy']要刪除指定位置的元素,用pop(i)方法,其中i是索引位置:
>>> classmates.pop(1) 'Jack' >>> classmates ['Michael', 'Bob', 'Tracy']要把某個元素替換成別的元素,可以直接賦值給對應的索引位置:
>>> classmates[1] = 'Sarah' >>> classmates ['Michael', 'Sarah', 'Tracy']list里面的元素的數據類型也可以不同,比如:
>>> L = ['Apple', 123, True]list元素也可以是另一個list,比如:
>>> s = ['python', 'java', ['asp', 'php'], 'scheme'] >>> len(s) 4要注意s只有4個元素,其中s[2]又是一個list,如果拆開寫就更容易理解了:
>>> p = ['asp', 'php'] >>> s = ['python', 'java', p, 'scheme']要拿到'php'可以寫p[1]或者s[2][1],因此s可以看成是一個二維數組,類似的還有三維、四維……數組,不過很少用到。
如果一個list中一個元素也沒有,就是一個空的list,它的長度為0:
總結
以上是生活随笔為你收集整理的python里面的list的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 惯性矩和偏心距描述器
- 下一篇: 添加中文数据出现问号_怪物猎人世界绚辉龙