python基础

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’]

Posted in 未分类

发表评论