首頁  >  文章  >  後端開發  >  python基礎-list

python基礎-list

巴扎黑
巴扎黑原創
2016-12-03 09:43:341077瀏覽

1、list建立

new_list1 = ['TV','Car','Cloth','Food']
new_list2 = list(['TV','Car','Cloth','Food'])
print (new_list1)
print (new_list2)
運行結果:
['TV', 'Car', 'Cloth', 'Food']
['TV', 'Car', 'Cloth', 'Food']

2、list常用的方法:

 1. append

new_list1 = ['TV','Car','Cloth','Food']
print (new_list1)
new_list1.append('Water') #追加'water'
print (new_list1)   
運行結果:
['TV', 'Car', 'Cloth', 'Food']
['TV', 'Car', 'Cloth', 'Food', ' Water']

 2.count

new_list1 = ['TV','Car','Cloth','Food','Food']
print (new_list1.count('Food')) #統計'food '在清單中的次數=> 2次

 3.extend

new_list1 = ['TV','Car','Cloth','Food','Food']
new_list1.extend([11,22 ,33,'Car'])
print (new_list1)   
運行結果:
['TV', 'Car', 'Cloth', 'Food', 'Food', 11, 22, 33, 'Car']

 4.sort

new_list1 = ['TV','Car','Cloth','Food','Food']
print (new_list1)
new_list1.sort() #排序
print (new_list1)
new_list1.sort() #排序
print (new_list1)
new_list1.sort(reverse=True) #反向排序
print (new_list1)   
運作結果:
['TV', 'Car', 'Cloth', 'Food', 'Food']
['Car', 'Cloth', 'Food', 'Food', 'TV'] #正向排序結果

['TV', 'Food', 'Food', 'Cloth', 'Car'] #反向排序結果

 5. len

new_list1 = ['TV','Car','Food','Cloth','Food']

print (len(new_list1)) => 5 #列印元素的數量

 .remove

new_list1 = ['TV','Car','Food','Cloth','Food']

new_list1.remove('Food')
print (new_list1)
運行結果:

[TV ', 'Car', 'Cloth', 'Food'] #remove會刪除找到的第一個相同元素

 7.pop

new_list1 = ['TV','Car','Food','Cloth ','Food']
new_list1.pop() #隨機刪除一個元素
print (new_list1)
new_list1.pop(2) #指定刪除某個元素
print (new_list1)
運行結果為:
['TV' , 'Car', 'Food', 'Cloth']

['TV', 'Car', 'Cloth'] #,此處刪除的是第3個元素'Food'

 8.index

new_list1 = ['TV','Car','Food','Cloth','Food']
print (new_list1.index('Food')) #傳回指定元素的index值,相同元素傳回查找到的第一筆

運行結果為:2

 9.insert

new_list1 = ['TV','Car','Food','Cloth','Food']
new_list1.insert(2,'HAHAHA')  #在指定的位置插入元素
print (new_list1)
運行結果為:

['TV', 'Car', 'HAHAHA', 'Food', 'Cloth', 'Food']


🎜🎜
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn