目录
1 元组
1.1 创建和访问一个元组
1.Python的元组与列表类似,不同之处在于tuple被创建之后就不能进行修改,类似于字符串。
2.元组使用小括号,列表使用方括号。
t1 = (1,10.31,"python")
t2 = 1,10.31,"python"
print(t1,type(t1))
>>>(1, 10.31, 'python') <class 'tuple'>
print(t2,type(t2))
>>>(1, 10.31, 'python') <class 'tuple'>
1.创建元组可以使用小括号,也可以什么都不用,为了可读性,还是建议使用小括号。
2.元组中只包含一个元素,需要在元素后面天剑逗号,否则括号会被当做运算符使用。
temp = (1)
print(type(temp))
>>><class 'int'>
temp = (2,3,4)
print(type(temp))
>>><class 'tuple'>
temp = []
print(type([]))
>>><class 'list'>
temp = ()
print(type(temp))
>>><class 'tuple'>
temp =(1,)
print(type(temp))
>>><class 'tuple'>
print(8 * (8))
>>>64
print(8 * (8,))
>>>(8, 8, 8, 8, 8, 8, 8, 8)
创建二维元组
nested = (1,10.31,"py"),("py",1)
print(nested)
>>>((1, 10.31, 'py'), ('py', 1))
元组中可以用整数来对他进行索引和切片,不严谨的讲,前者是获取单个元素,后者是获取一个元组元素。
print(nested[0])
>>>(1, 10.31, 'python')
print(nested[0][0], nested[0][1], nested[0][2])
>>>1 10.31 python
print(nested[0][0:2])
>>>(1, 10.31)
1.2 更新和删除一个元组
week = ('Monday', 'Tuesday', 'Thursday', 'Friday')
week = week[:2] + ('wen',) + week[2:]
print(week)
>>>('Monday', 'Tuesday', 'wen', 'Thursday', 'Friday')
t1 = (1, 2, 3, [4, 5, 6])
print(t1)
>>>(1, 2, 3, [4, 5, 6])
t1[3][0] = 9
print(t1)
>>>(1, 2, 3, [9, 5, 6])
元组有不可更改 (immutable) 的性质,因此不能直接给元组的元素赋值,但是只要元组中的元素可更改 (mutable),那么我们可以直接更改其元素,注意这跟赋值其元素不同。
1.3 元组相关操作符
1.比较操作符
2.逻辑操作符
3.链接操作符 +
4.重复操作符 *
5.成员关系操作符 in,not in
元组拼接有两种方式,用「加号 +」和「乘号 *」,前者首尾拼接,后者复制拼接。
t1 = (1,2,3,4)
t2 = ('python',"python")
t3 = t1 + t2
print(t3)
>>>(1, 2, 3, 4, 'python', 'python')
t4 = t2 * 2
print(t4)
>>>('python', 'python', 'python', 'python')
1.4 内置方法
元组大小和内容都不可更改,因此只有count和index两种方法。
t = (1,10.31,"python")
print(t.count("python"))
>>>1
print(t.index(10.31))
>>>1
1.count("python") 是记录在元组t 中该元素出现几次。
2.inde(10.31) 是找到该元素在元素t的索引。
1.5 解压元组
解压一维元组(有几个元素左边括号就定义几个变量)
t = (1,10.31,"python")
(a,b,c) = t
print(a,b,c)
>>>1 10.31 python
t = (1, 10.31, ('OK', 'python'))
(a, b, (c, d)) = t
print(a, b, c, d)
>>>1 10.31 OK python
如果你只想要元组中几个元素,用通配符【*】。
t = 1, 2, 3, 4, 5
a, b, *rest, c = t
print(a, b, c)
>>>1 2 5
print(rest)
>>>[3, 4]
上面把多个元素都给了变量rest 如果不在乎变量rest 那么就用通配符* 加下划线_
a,b,*_ = t
print(a,b)
>>>1 2