首页 > 后端开发 > Python教程 > python基础-list

python基础-list

巴扎黑
发布: 2016-12-03 09:43:34
原创
1107 人浏览过

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


相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板