Python 中 list 与 tuple (列表与元组)

偏执的太偏执、 2022-05-30 07:27 345阅读 0赞

Python


list 列表、

有序、存储多个元素、可使用索引、索引从0开始、可以截取、插入、删除、修改、一个列表可以作为另一个列表中的元素

  1. >>> list_name=['a','b','c',1,2,3]

通过索引获取列表中的元素:list_name[ ]

  1. >>> list_name[0]
  2. 'a'
  3. >>> list_name[-1]
  4. 3
  5. >>> list_name[2:3]
  6. ['c']
  7. >>> list_name[2:2]
  8. []
  9. >>> list_name[3:-1]
  10. [1, 2]
  11. >>> list_name[2:6]
  12. ['c', 1, 2, 3]
  13. >>> list_name[2:9]
  14. ['c', 1, 2, 3]
  15. >>> list_name[2:]
  16. ['c', 1, 2, 3]

向列表中插入元素:append() 向列表的尾部添加一个新的元素 / insert()将元素插入到索引指定的位置

  1. >>> list_name.append('z')
  2. >>> print(list_name)
  3. ['a', 'b', 'c', 1, 2, 3, 'z']
  4. >>> list_name.insert(3,'d')
  5. >>> print(list_name)
  6. ['a', 'b', 'c', 'd', 1, 2, 3, 'z']

删除列表中的元素:pop()删除列表中的元素 / del 删除列表中的元素

  1. >>> list_name.pop()
  2. 'z'
  3. >>> print(list_name)
  4. ['a', 'b', 'c', 'd', 1, 2, 3]
  5. >>> list_name.pop(3)
  6. 'd'
  7. >>> print(list_name)
  8. ['a', 'b', 'c', 1, 2, 3]
  9. >>> del list_name[5]
  10. >>> print(list_name)
  11. ['a', 'b', 'c', 1, 2]

修改列表中的元素:根据索引替换某个元素/一个列表可以做为另一个列表中的元素

  1. >>> list_name[0]='z'
  2. >>> print(list_name)
  3. ['z', 'b', 'c', 1, 2]
  4. >>> list1=[True,'哈','q',2]
  5. >>> print(list_name)
  6. ['z', 'b', 'c', 1, 2]
  7. >>> list_name[1]=list1
  8. >>> print(list_name)
  9. ['z', [True, '哈', 'q', 2], 'c', 1, 2]
  10. >>> list_name[1][1]
  11. '哈'

Python列表函数&方法

函数:
1 cmp(list1, list2) 比较两个列表的元素
2 len(list) 列表元素个数
3 max(list)返回列表元素最大值
4 min(list) 返回列表元素最小值
5 list(seq) 将元组转换为列表
方法:
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]) 对原列表进行排序


tuple 元组、

元组与列表类似、元组的元素不能修改、元组使用圆括号、列表使用方括号、
任意无符号的对象、以逗号隔开、默认为元组

元组中只包含一个元素时,需要在元素后面添加逗号

  1. >>> tuple1=('a','b','c',1,2,3)
  2. >>> print(tuple1)
  3. ('a', 'b', 'c', 1, 2, 3)
  4. >>> tuple2=(1)
  5. >>> print (tuple2)
  6. 1
  7. >>> tuple3=(1,)
  8. >>> print(tuple3)
  9. (1,)
  10. >>> tuple4=()
  11. >>> print(tuple4)
  12. ()

可以使用索引获取元组中的元素:

  1. >>> tuple1[0]
  2. 'a'
  3. >>> tuple1[1:5]
  4. ('b', 'c', 1, 2)

del删除整个元组:

  1. >>> del tuple1
  2. >>> print(tuple1)
  3. Traceback (most recent call last):
  4. File "<stdin>", line 1, in <module>
  5. NameError: name 'tuple1' is not defined

元组内置函数
1 cmp(tuple1, tuple2) 比较两个元组元素。
2 len(tuple) 计算元组元素个数。
4 min(tuple)返回元组中元素最小值。
5 tuple(seq) 将列表转换为元组。

发表评论

表情:
评论列表 (有 0 条评论,345人围观)

还没有评论,来说两句吧...

相关阅读