Python:列表

List:列表

List列表是python中最常用的数据类型。列表中元素的类型可以不相同,它支持数字,字符串甚至可以包含列表(所谓嵌套)。列表定义格式:list = [obj1,obj2,obj3,…],与其他编程语言的数组概念相似,下标从0开始,即list[0]=obj1。列表截取的语法格式:变量[头下标:尾下标]

访问列表

可以使用下标索引来访问列表的单个元素,也可以使用方括号的方式来截取子列表来进行访问。例如:

 
  1. #!/usr/bin/python3.5
  2. L=[] #创建空列表
  3. list = ['hello','python','world',110,4.5]
  4. print(list) #打印所有元素
  5. #['hello', 'python', 'world', 110, 4.5]
  6. print(list[1:4]) #第2个到第5个
  7. #['python', 'world', 110]
  8. print(list[2:]) #第2个到最后
  9. #['world', 110, 4.5]
  10. print(list[:3]) #开始到第3个
  11. #['hello', 'python', 'world']
  12. print(list[1]) #第1个元素(注意:返回元素而不是列表,所以返回值没有中括号)
  13. #python
  14. print(list * 2) #重复两次list
  15. #['hello', 'python', 'world', 110, 4.5, 'hello', 'python', 'world', 110, 4.5]
  16. list[4] = 2.5 #允许修改列表元素值
  17. print(list)
  18. #['hello', 'python', 'world', 110, 2.5]
  19. del list[2] #删除第3个元素
  20. print(list)
  21. #['hello', 'python', 110, 2.5]

Python

列表其他常用操作

列表最常用的操作除了截取访问之外,还有求列表元素个数、列表连接、插入删除元素、判断元素是否存在于列表等常用操作。

 
  1. #/usr/bin/python3.5
  2. list1 = [1,2,3,4,5]
  3. list2 = [6,7,8]
  4. print(len(list1)) #len(list):列表元素个数
  5. #5
  6. print(list1+list2) #list1+list2:列表拼接
  7. #[1, 2, 3, 4, 5, 6, 7, 8]
  8. print(list2 * 2) #list*n:列表重复
  9. #[6, 7, 8, 6, 7, 8]
  10. print(9 in list1) #obj in list:判断元素是否在列表中
  11. #False
  12. for x in list1:print(x,end="+") #列表迭代
  13. #1+2+3+4+5+
  14. print(max(list1)) #max(list):返回列表最大值
  15. #5
  16. list1.append(6) #list.append(obj):列表尾部添加元素obj
  17. print(list1)
  18. #[1, 2, 3, 4, 5, 6]
  19. list1.append(6)
  20. list1.count(6) #list.count(obj):计算obj在列表出现的次数
  21. #2
  22. list1.insert(0,7) #list.insert(index,obj):在下标为index的位置,插入obj
  23. print(list1)
  24. #[7, 1, 2, 3, 4, 5, 6, 6]

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值