欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

python基础-list

程序员文章站 2022-05-23 20:43:26
...
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']