python组合数据类型详解——列表

列表是包含0个或多个对象引用的有序序列,属于序列类型,没有长度限制,可自由增删元素,使用灵活。

序列类型的通用操作符和函数

操作符和函数描述
x in s如果x是s的元素,返回True,否则返回False
x not in s如果x不是s的元素,返回True,否则返回False
s + t连接s和t
s * n 或者 n * s将s复制n次
s[i]索引,返回序列的第i个元素
s[i:j]分片,返回包含序列s第i到j个元素的子序列(不包含第j个元素)
s[i:j:k]步骤切片,返回包含序列s第i到j个元素以k为步数的子序列
len(s)序列s的元素个数
min(s)序列s的最小元素
max(s)序列s的最大元素
s.index(x[,i[,j]])序列s中从i开始到j位置中第一次出现元素x的位置
s.count(x)序列s中出现x的总次数

列表类型特有的方法

  • list.append(x)将x元素添加至列表尾部
>>> L=[1,2,3,4,5]
>>> L.append(6)
>>> print(L)
[1,2,3,4,5,6]
  • list.clear()删除列表中所有的元素,但保留列表对象
>>> L=[1,2,3,4,5]
>>> L.clear()
>>> print(L)
[]
  • list.copy()返回列表对象的浅拷贝
>>> L=[1,2,3,4,5]
>>> L.append(6)
>>> L.copy()
[1, 2, 3, 4, 5, 6]
  • list.count(x)返回指定元素x在列表中出现次数
>>> L = [1,1,2,3,4,5]
>>> L.count(1)
2
  • list.extend(L)将列表L中的所有元素添加至列表尾部
>>> L = [1,1,2,3,4,5]
>>> L1 = ["python"]
>>> L1.extend(L)
>>> print(L1)
['python', 1, 1, 2, 3, 4, 5]
  • list.index(x)返回x的首个元素的下标
>>> L = [1,1,2,3,4,5]
>>> L.index(1)
0
  • list.insert(index,x)在列表指定位置index处添加元素x
>>> L = [1,1,2,3,4,5]
>>> L.insert(0,"python")
>>> print(L)
['python', 1, 1, 2, 3, 4, 5]
  • list.pop(index)删除并返回列表对象指定位置的元素(默认index为-1)
>>> L = ['python', 1, 1, 2, 3, 4, 5]
>>> L.pop(0)
'python'
>>> x=[1,2,3,2,3]
>>> x.pop()
>>> print(x)
[1,2,3,2]
  • list.remove(x)在列表中删除首次出现的元素x
>>> L = ['python', 1, 1, 2, 3, 4, 5]
>>> L.remove(1)
>>> print(L)
['python', 1, 2, 3, 4, 5]
  • list.reverse()对列表元素进行原地倒序
>>> L = ['python', 1, 1, 2, 3, 4, 5]
>>> L.reverse()
>>> print(L)
[5, 4, 3, 2, 1, 1, 'python']
  • list.sort(reverse=False)对列表元素进行原地排序(升序、降序,当reverse为False(默认)时,升序排序;当reverse为True时,降序排序)
    在使用sort()方法的时候,我们要注意以下两点
    1. 不能对既有数字又有字符串值的列表排序
    2. sort()方法对字符串排序时,使用的是:“ASCII 字符顺序”,不是实际的字典顺序。空格<数字<大写字母<小写字母
>>> L = ['python', 1, 1, 2, 3, 4, 5]
>>> L.sort()
Traceback (most recent call last):
  File "<pyshell#56>", line 1, in <module>
    L.sort()
TypeError: '<' not supported between instances of 'int' and 'str'
>>> L = [1, 1, 2, 3, 4, 5]
>>> L.sort()
>>> print(L)
[1, 1, 2, 3, 4, 5]
>>> L = [1, 1, 2, 3, 4, 5]
>>> L.sort(reverse=True)
>>> print(L)
[5, 4, 3, 2, 1, 1]
>>> L = ["A","a","C","c"]
>>> L.sort()
>>> print(L)
['A', 'C', 'a', 'c']

列表推导式

[新元素表达式 for 临时变量 in 可迭代对象 if 条件表达式]

>>> x = [1,2,3,4,5,6,7,8,9,10]
>>> [i*i for i in x if i % 3 == 0]
[9, 36, 81]

如果想要了解其他组合数据类型,可以点击这里

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值