python的列表list的使用方法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python的列表list的使用方法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1841字,纯文字阅读大概需要3分钟。
内容图文
![python的列表list的使用方法](/upload/InfoBanner/zyjiaocheng/763/9d6f73b2b91a41379b6b3793b026e213.jpg)
1、什么是列表
列表是由一系列按特定顺序排列的元素,元素之间可以没有任何关系;可以创建空列表,也可以将任何东西添加进列表。
列表用 [ ] 表示:
cars = ['golf', 'magotan', 'sagitar', 'jetta']
2、列表序列是从0开始
1 cars = ['golf', 'magotan', 'sagitar', 'jetta'] 2 print(cars[0]) 3 golf 4 print(cars[2]) 5 sagitar
3、首字母大写
1 cars = ['golf', 'magotan', 'sagitar', 'jetta'] 2 print(cars[0].title()) 3 Golf
4、遍历列表的方法
⑴
cars = ['golf', 'magotan', 'sagitar', 'jetta'] for i in cars: print(i)
⑵
cars = ['golf', 'magotan', 'sagitar', 'jetta'] length = len(cars) i = 0 while i < length: print(cars[i]) i+=1
5、append
添加元素,整体添加
cars = ['golf', 'magotan', 'sagitar', 'jetta'] tem = ['bora', 't-roc'] cars.append(tem) print(cars) # ['golf', 'magotan', 'sagitar', 'jetta', ['bora', 't-roc']]
6、extend
添加元素,将另一个集合中的元素逐一添加到列表中
cars = ['golf', 'magotan', 'sagitar', 'jetta'] tem = ['bora', 't-roc'] cars.extend(tem) print(cars) # ['golf', 'magotan', 'sagitar', 'jetta', 'bora', 't-roc']
7、insert
在指定index索引位置前插入元素
cars = ['golf', 'magotan', 'sagitar', 'jetta'] cars.insert(2, 'tayron') print(cars) #['golf', 'magotan', 'tayron', 'sagitar', 'jetta']
8、修改元素
cars = ['golf', 'magotan', 'sagitar', 'jetta'] cars[0] = 'tayron' print(cars) # ['tayron', 'magotan', 'sagitar', 'jetta']
9、in(包含结果为true,不包含结果为false), not in(不包含结果为False,包含结果为True), index, count
cars = ['tayron', 'jetta', 'magotan', 'sagitar', 'jetta', 'bora', 't-roc']
love_car = 'tayron'
if love_car in cars:
print('包含有')
# ------------------------
cars.index('jetta', 2, 4)
# jetta 在1和4的位置,所以报错 ''' Traceback (most recent call last): File "<pyshell#41>", line 1, in <module> cars.index('jetta', 2, 4) ValueError: 'jetta' is not in list
'''
cars.count('bora')
# 5
10、删除元素del, pop, remove
del:根据下标进行删除
pop:删除最后一个元素
remove:根据元素的值进行删除
11、排序sort, reverse
sort方法是将list按特定顺序重新排列,默认为由小到大,参数reverse=True可改为倒序,由大到小。
reverse方法是将list逆置。
内容总结
以上是互联网集市为您收集整理的python的列表list的使用方法全部内容,希望文章能够帮你解决python的列表list的使用方法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。