跳转至

python-study-Tuple

rhyme = (1,2,3,4,5, "上山打老虎")
rhyme
1
(1, 2, 3, 4, 5, '上山打老虎')
rhyme[0]
1
1
rhyme[-1]
1
'上山打老虎'

不支持修改

rhyme[1]=10#不支持修改
1
2
3
4
5
6
7
8
9
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

~\AppData\Local\Temp\ipykernel_17308\1184099170.py in <module>
----> 1 rhyme[1]=10


TypeError: 'tuple' object does not support item assignment
rhyme[:3]
1
(1, 2, 3)
rhyme[3:]
1
(4, 5, '上山打老虎')
rhyme[:]
1
(1, 2, 3, 4, 5, '上山打老虎')
rhyme[::2]
1
(1, 3, 5)
rhyme[::-1]
1
('上山打老虎', 5, 4, 3, 2, 1)
nums= (3,1,9,6,8,3,5,3)
nums.count(3)
1
3
heros=("蜘蛛侠","绿巨人","黑寡妇")
heros.index("黑寡妇")
1
2
s=(1, 2, 3)
t=(4,5,6)
s+t
1
(1, 2, 3, 4, 5, 6)
s*3
1
(1, 2, 3, 1, 2, 3, 1, 2, 3)

,用于切割元组

w=s, t
w
1
((1, 2, 3), (4, 5, 6))
for each in s:
    print(each)
1
2
3
1
2
3
1
2
3
for i in w:
    for each in i:
        print(each)
1
2
3
4
5
6
1
2
3
4
5
6
s=(1,2,3,4,5)
[each*2 for each in s]
1
[2, 4, 6, 8, 10]
(each*2 for each in s) #生成器
1
<generator object <genexpr> at 0x00000241A7CCF200>

没有元组推导式

x=(520)
x
1
520
type(x)
1
int
x = (520,)
x
1
(520,)
type(x)
1
tuple

打包和解包

t=(123,"FishC",3.14)
t
1
(123, 'FishC', 3.14)
x, y, z = t
x
1
123
y
1
'FishC'
z
1
3.14

both applyed to list and tuple

t=[123,"FishC",3.14]
x, y, z = t
x
1
123
y
1
'FishC'
z
1
3.14

左右变量数量一致

a, b, *c="FishC"
a
1
'F'
b
1
'i'
c
1
['s', 'h', 'C']

多重赋值

x, y = 10, 20
x
1
10
y
1
20
_=(10,20)
x, y = _
x
1
10
y
1
20

security

s=[1,2,3]
t=[4,5,6]
w=(s,t)
w
1
([1, 2, 3], [4, 5, 6])
w[0][0]=0
w
1
([0, 2, 3], [4, 5, 6])

此时对于元组中可变的列表,依然可以更改