Python的列表和元组

一 创建和操作列表

1、介绍
列表是最常用的Python数据类型,它可以作为一个方括号内的逗号分隔值出现。
列表的数据项不需要具有相同的类型。
创建一个列表,只要把逗号分隔的不同的数据项使用方括号括起来即可。
2、常用的列表操作
序号 方法
1 list.append(obj)
在列表末尾添加新的对象
2 list.count(obj)
统计某个元素在列表中出现的次数
3 list.extend(seq)
在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
4 list.index(obj)
从列表中找出某个值第一个匹配项的索引位置
5 list.insert(index, obj)
将对象插入列表
6 list.pop(obj=list[-1])
移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
7 list.remove(obj)
移除列表中某个值的第一个匹配项
8 list.reverse()
反向列表中元素
9 list.sort([func])
对原列表进行排序
10 list.clear()
清空列表
11 list.copy()
复制列表
3、举例
  1. >>> list =[]
  2. >>> list.append(1)
  3. >>> list.count(2)
  4. 0
  5. >>> list.extend([2,3,5,4])
  6. >>> list
  7. [1,2,3,5,4]
  8. >>> list.index(5)
  9. 3
  10. >>> list.insert(2,6)
  11. >>> list
  12. [1,2,6,3,5,4]
  13. >>> list.pop(2)
  14. 6
  15. >>> list
  16. [1,2,3,5,4]
  17. >>> list.remove(5)
  18. >>> list
  19. [1,2,3,4]
  20. >>> list.reverse()
  21. >>> list
  22. [4,3,2,1]
  23. >>> list.sort()
  24. >>> list
  25. [1,2,3,4]
 
二 创建和操作元组
1、介绍
Python 的元组与列表类似,不同之处在于元组的元素不能修改。
元组使用小括号,列表使用方括号。
元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
2、举例
  1. >>> list
  2. [1,2,3,4]
  3. >>> tuple =('a','b','c')
  4. >>> list.insert(4,tuple)
  5. >>> list
  6. [1,2,3,4,('a','b','c')]
  7. >>> list[4]
  8. ('a','b','c')
  9. >>> list[1:4]
  10. [2,3,4]
  11. >>> tuple[2]
  12. 'c'
  13. >>> tuple[1:-1]
  14. ('b',)

猜你喜欢

转载自cakin24.iteye.com/blog/2381529