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'] #正向排序結果
5. len
new_list1 = ['TV','Car','Food','Cloth','Food']
.remove
new_list1 = ['TV','Car','Food','Cloth','Food']
new_list1.remove('Food')
print (new_list1)
運行結果:
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']
8.index
new_list1 = ['TV','Car','Food','Cloth','Food']
print (new_list1.index('Food')) #傳回指定元素的index值,相同元素傳回查找到的第一筆
9.insert
new_list1 = ['TV','Car','Food','Cloth','Food']
new_list1.insert(2,'HAHAHA') #在指定的位置插入元素
print (new_list1)
運行結果為: