在python中,列表是由一系列按特定順序排列的元素組成,用來表示列表,並用英文逗號分隔其中的元素。例如:
同大多數程式語言一樣,python中的列表元素下表也是從0開始計數的,使用[i]訪問列表中的元素,例如:>>> print(list);
['h', 'e']
>>> list = [1,2,3,4]
>>> print(list);
[1, 2, 3, 4]
>>> list = ["hello",'world']
>>> print(list);
['hello', 'world']
>>>
當超出列表元素索引時,會報出「indexerror: list index out of range」的異常資訊。>>> list = ['ni','hao','hello','world']
>>> print(list[0]);
ni>>> print(list[4]);
traceback (most recent call last):
file "", line 1, in indexerror: list index out of range
>>>
另外,在訪問列表時,負數下標代表從後往前數的元素,例如:
列表的元素也可以是另外乙個陣列,例如:>>> list = ['i','am','very','good'];
>>> print(list[-1])
good
>>> print(list[-2])
very
>>> list = ['haha','hehe',[1,2,3]]
>>> print(list)
['haha', 'hehe', [1, 2, 3]]
>>>
這裡需要注意len()函式的用法,是len(list)。>>> list = ['i','am','very','good'];
>>> print(len(list));
4>>> print(list[len(list)-1])
good
>>> print(list[-1])
good
>>> print(list[-2])
very
2、在列表中隨機位置插入新的元素:insert()函式>>> list = ['i','am', 'very','good']
>>> print(list);
['i', 'am', 'very', 'good', '!']
>>>
仍以上面的list為例,在「am」之後的位置新增乙個「so」的元素:
同理,insert()的下標也可以為負數,從後面數往前插入:>>> print(list);
['i', 'am', 'very', 'good', '!']
>>> list.insert(2,'so')
>>> print(list)
['i', 'am', 'so', 'very', 'good', '!']
>>>
直接使用list[i] = newvalue,進行複製操作即可:>>> list.insert(-1,'haha');
>>> print(list)
['i', 'am', 'so', 'very', 'good', 'haha', '!']
>>>
1、根據索引刪除元素:del語句>>> list = [1,2,3]
>>> list[0]=0
>>> print(list)
[0, 2, 3]
>>>
2、根據值刪除元素:remove()函式c:\users\administrator>python
python 3.7.0 (v3.7.0:1bf9cc5093, jun 27 2018, 04:59:51) [msc v.1914 64 bit (amd64)] on win32
>>> list = [1,2,3,4]
>>> del list[0]
>>> print(list)
[2, 3, 4]
>>> del list[-1]
>>> print(list)
[2, 3]
>>> del list[8]
traceback (most recent call last):
file "", line 1, in indexerror: list assignment index out of range
>>>
remove函式只刪除列表中第乙個指定的值:
3、pop()函式:>>> list = ['one','two','three']
>>> list.remove('two')
>>> print(list)
['one', 'three']
>>> list2 = [1,2,2,3,4]
>>> list2.remove(2)
>>> print(list2)
[1, 2, 3, 4]
>>>
pop()函式刪除列表末尾元素,並且返回該元素:
pop(i)函式刪除第i個位置的元素,並返回該元素:>>> list = [1,2,3,4,5]
>>> temp = list.pop()
>>> print(list)
[1, 2, 3, 4]
>>> print(temp)
5>>>
>>> list = [1,2,3,4,5,6]
>>> temp = list.pop(2)
>>> print(list)
[1, 2, 4, 5, 6]
>>> print(temp)
3>>>
python學習(三) 列表
list是類,由中括號括起來,分割麼個元素,列表中元素可以是數字,字串,列表,布林值 所有都可以放進去 可以修改 li 1,asd true,小二 1,2 物件 索引取值 print li 3 切片,結果也是列表 print li 1 1 1 列表的修改 刪除 li 1,asd true,小二 1,...
Python學習(三) 列表和元組
序列是python中最基本的一種資料結構,序列上的每乙個元素都會指定乙個數字 或稱之為索引 以0開頭類推。在python的6個序列中,列表和元祖是最常見的。序列都可以進行的操作包括 索引,切片 加 乘 檢查成員。除此之外,序列都可以進行確定序列長度,確定最大元素和最小元素的方法。python中的元素...
Python學習筆記三 列表(一)
列表是一些按特定順序排列的元素組成,元素之間沒有關係 如 names li hua kang kang han mei mei numbers 1,2,5,88,3 用位置或索引訪問,索引是從0開始,若想直接訪問最後一位,則索引為 1 numbers 1 2,5 88,3 names li hua ...