python基础-list

巴扎黑
Lepaskan: 2016-12-03 09:43:34
asal
1107 orang telah melayarinya

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(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 #打印元素的个数

 6.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']


Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan