1. 程式人生 > >python 列表相關內容

python 列表相關內容

sort 雜項 出現 wan 增加 獲取 列表 .so 判斷


python 列表相關內容

1、增加
2、修改
3、切片
4、清空
5、刪除
6、雜項

#定義兩個列表
name2 = [1,2,3,4]
name_list = [‘zhang‘,‘wang‘,‘li‘,‘liu‘,‘yang‘ ,[‘ding‘,‘guo‘],‘zhao‘]

1.列表的追加操作:
name_list.append(name2)
print(name_list)
輸出結果:
[‘zhang‘, ‘wang‘, ‘li‘, ‘liu‘, ‘yang‘, [‘ding‘, ‘guo‘], ‘zhao‘, [1, 2, 3, 4]]

name2.insert(2,7)

2.列表修改:
name_list[2]=‘WANG‘
print(name_list)
[‘zhang‘, ‘wang‘, ‘WANG‘, ‘liu‘, ‘yang‘, [‘ding‘, ‘guo‘], ‘zhao‘]

3.列表切片:
秘笈:跟鴕鳥一樣,顧首不顧尾
輸入:
print(name_list[2:5])
print(name_list[1:-1])
print(name_list[:-2])
print(name_list[2:])
print(name_list[::2])
輸出:
[‘zhang‘, ‘wang‘, ‘WANG‘, ‘liu‘, ‘yang‘, [‘ding‘, ‘guo‘], ‘zhao‘]
[‘WANG‘, ‘liu‘, ‘yang‘]
[‘wang‘, ‘WANG‘, ‘liu‘, ‘yang‘, [‘ding‘, ‘guo‘]]
[‘zhang‘, ‘wang‘, ‘WANG‘, ‘liu‘, ‘yang‘]
[‘WANG‘, ‘liu‘, ‘yang‘, [‘ding‘, ‘guo‘], ‘zhao‘]
[‘zhang‘, ‘WANG‘, ‘yang‘, ‘zhao‘]


4.列表清空:
輸入:
name2.clear()
print(name2)
輸出結果:
[]

5.列表的刪除操作:
1、remove 方法
name_list.remove(‘liu‘)
2、pop 方法
name_list.pop(4)
3、del 方法
del name_list[2]
輸入:
name_list.remove(‘liu‘)
print(name_list)
name_list.pop(4)
print(name_list)
del name_list[2]
print(name_list)

輸出
[‘zhang‘, ‘wang‘, ‘li‘, ‘yang‘, [‘ding‘, ‘guo‘], ‘zhao‘]
[‘zhang‘, ‘wang‘, ‘li‘, ‘yang‘, ‘zhao‘]
[‘zhang‘, ‘wang‘, ‘yang‘, ‘zhao‘]

6.雜項

判斷某一個元素出現的次數:
print(name_list.count(‘li‘))

獲取某個給定元素的索引位置:
print(name_list.index(‘yang‘))
列表翻轉:
name_list.reverse()
print(name_list)
輸出:
[‘zhao‘, [‘ding‘, ‘guo‘], ‘yang‘, ‘liu‘, ‘li‘, ‘wang‘, ‘zhang‘]

列表排序:
輸入:
name2.insert(2,6)
print(name2)
name2.sort()
print(name2)

輸出:
[1, 2, 6, 3, 4]
[1, 2, 3, 4, 6]

列表拷貝:

name2 = name_list.copy()
print(name2)
輸出:
[‘zhang‘, ‘wang‘, ‘li‘, ‘liu‘, ‘yang‘, [‘ding‘, ‘guo‘], ‘zhao‘]

python 列表相關內容