Python列表是Python中很重要的一個數據類型。列表中的每個數據稱之為列表的項。列表中的每一項使用英文逗號進行分隔,所有項放在方括號中。同時,列表中的每項的數據類型不一定相同。我們可以對列表項進行增,改,刪操作。
lst1 = [] #創建一個空的列表
lst2 = ['Python', 'Java', 'R', 'SPSS'] # 字符串列表
lst3 = [1, 2, 3, 4, 5] # 整型列表
lst4 = [1, 'Python', 2, 'Java', 'R', 3] # 混合數據類型的列表
# 使用print方法輸出列表
print(lst1)
print(lst2)
print(lst3)
print(lst4)
上面代碼執行后生成下圖所示的結果:
列表中的每一項都有其位置索引,從列表左側進行編號的話是從 0 開始的,從右邊進行編號的話,是從 -1 開始的。我們可以使用 list_name[index] 的方式來訪問列表中某一項的值:
lang = ['Python', 'C#', 'R', 'Java', 'PHP']
s = lang[0] # 索引為0的項
print(s)
print(lang[2]) # 索引為2的項
s1 = lang[-1] # 訪問最后一項
print(s1)
輸出結果為:
列表定義完后,如修改里面某項的值,可以使用 list_name[index] = newvalue 的形式來完成。
like_fruits = ['apple', 'pear', 'banana', 'orange']
print('更新前的值:', end = '')
print(like_fruits)
like_fruits[1] = 'berry' # 修改索引為1處的值
print('更新后的值:', end = '')
print(like_fruits)
like_fruits[-1] = 'mango'
print(like_fruits)
輸出結果:
更新前的值:['apple', 'pear', 'banana', 'orange']
從輸出結果來看,第2項(索引為1)的值已經被修改,在此基礎上,使用負數索引,把最后一項的值也修改了。
更新后的值:['apple', 'berry', 'banana', 'orange']
['apple', 'berry', 'banana', 'mango']
Python中提供了多種方式來刪除列表中的某一項。
# 定義一個顏色列表
list_colors = ['Red', 'Blue', 'Black', 'White', 'Pink', 'Green', 'Gray']
print('原列表:',list_colors)
# 使用 remove 刪除指定值的列表項
list_colors.remove('Green')
print('使用remove刪除/'Green/'后:', list_colors)
# 使用 del 刪除指定索引處的列表項
del list_colors[2]
print('使用del刪除索引2處的項后:', list_colors)
# 使用pop方法移除指定索引處的項
list_colors.pop(3)
print('使用pop方法刪除索引3處的項后:', list_colors)
輸出結果:
原列表: ['Red', 'Blue', 'Black', 'White', 'Pink', 'Green', 'Gray']
注意上面使用Remove方法來刪除列表中的項時,只能使用具體的值來刪除,不能使用索引(為什么呢?大家可以思考一下這個問題),并且要刪除的值必須在列表中存在,否則會報錯。使用pop時只能使用索引,不能使用值來刪除。
使用remove刪除'Green'后: ['Red', 'Blue', 'Black', 'White', 'Pink', 'Gray']
使用del刪除索引2處的項后: ['Red', 'Blue', 'White', 'Pink', 'Gray']
使用pop刪除索引3處的項后: ['Red', 'Blue', 'White', 'Gray']
Python中的 del 不僅能刪除列表中的某一項,還能將整個列表進行刪除,看下面的例子:
>>> lst = ['A', 'B', 'C']
>>> print(lst)
['A', 'B', 'C']
>>> del lst[1]
>>> print(lst)
['A', 'C']
>>> del lst
>>> print(lst)
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
print(lst)
NameError: name 'lst' is not defined
從上面的例子中可以看出,del把lst列表的定義給刪除了,內存中不存在lst,造成再次訪問時發生 NameError 錯誤。
能使用索引的方法,也可以使用負數索引從后面進行操作。
列表中又包含列表,稱之為嵌套列表。下面使用例子來說明其具體操作。
# 定義一個嵌套列表
list1 = ['武林網VEVB', 'http://www.companysz.com', ['Python', 'HTML', 'CSS'], 2008]
# 輸出原列表
print('原列表:', list1)
#訪問嵌套列表
print('list1[0]:',list1[0])
print('list1[2]:',list1[2])
print('list1[2][1]:',list1[2][1])
print('list1[2][-1]:',list1[2][-1])
# 修改嵌套列表項
list1[0] = '武林網'
print('修改[0]:',list1)
list1[2][2] = 'C#'
print('修改[2][2]', list1)
list1[2][-1] = 'SPSS'
print('修改[2][-1]', list1)
#刪除嵌套列表的項
list1[2].remove('SPSS')
print("[2].remove('SPSS')", list1)
list1[2].pop(0)
print('[2].pop[0]:', list1)
以上在Python中的輸出情況如下圖所示
除此之外,Python中還提供了多種函數以及相關的運算符完成對列表的相關操作,本站今后將繼續提供相關內容。
本文(完)
新聞熱點
疑難解答