標籤:python xtend 資料 反向 app ever try 列表方法 ica
列表是Python中最基本的資料結構。列表中的每個元素都分配一個數字作為它的位置索引,第一個索引是0,第二個索引是1,依此類推。列表的方法如下:先定義三個列表:
list1 = [‘python‘, ’hello‘, 100, 2000]list2 = [1, 7, 3, 4, 5]list3 = ["a", "b", "c", "d”]
1、在列表末尾一次性追加另一個序列中的多個值:
list1.extend(list2)print(list1)
結果:[‘physics‘, ‘chemistry‘, 1997, 2000, 1, 2, 3, 4, 5] 2、從列表中找出某個第一個匹配項的索引位置:
print(list1.index(‘hello’))
結果:1 3、統計某個元素在列表中出現的次數
print(list1.count(‘hello’))
結果:1 4、刪除列表中的一個元素,預設最後一個元素
print(list1.pop())print(list1)
結果:2000[‘python‘, ‘hello‘, 100] 5、列表中增加一個元素(在列表的2號位置後增加一個元素)
list1.insert(2,"world")print(list1)
結果:[‘python‘, ‘hello‘, ‘world‘, 100, 2000] 6、對列表進行排序
list2.sort()print(list2)
結果:[1, 3, 4, 5, 7] 7、刪除列表中的某個元素:
list2.remove(7)print(list2)
結果:[1, 3, 4, 5, ] 8、對列表進行反向排序
list1.reverse()print(list1)
結果:[2000, 100, ‘hello‘, ‘python’] 9、拷貝列表
list4 = list1.copy()print(list4)
結果:[‘python‘, ‘hello‘, 100, 2000] 10、清空列表
list1.clear()print(list1)
結果:[] 11、在列表尾部添加一個元素
list1.append(1000)print(list1)
結果:[‘python‘, ‘hello‘, 100, 2000, 1000]
python-列表方法介紹