python元组

  • 有序
  • 可重复
  • 不可更改

定义

符号使用()

元组的创建

空元组的创建

单元素元组的创建,需要在单元素后面添加逗号

tp=()
print(type(tp))
tp=("abc")
print(type(tp))
tp=("abc",)
print(type(tp))

'''
<class 'tuple'>
<class 'str'>
<class 'tuple'>

'''

多元素元组的创建,包含多种数据类型

常见操作

(1)拼接

tp1 = (1, 3, ["a", "b"])
tp2 = ("gh", "123")
tp3 = tp1 + tp2
print(tp3)
'''
(1, 3, ['a', 'b'], 'gh', '123')
'''

(2)重复

tp2 = ("gh", "123")
print(tp2 * 3)
'''
('gh', '123', 'gh', '123', 'gh', '123')
'''

(3)索引(偏移) ,切片

tp1 = (1, 3, ["a", "b"])
tp2 = ("gh", "123")
tp3 = tp1 + tp2
print(tp3)
print(tp2 * 3)
print(tp1[2])
print(tp1[0:1])
print(tp3[1:3])

'''
(1, 3, ['a', 'b'], 'gh', '123')
('gh', '123', 'gh', '123', 'gh', '123')
['a', 'b']
(1,)
(3, ['a', 'b'])

'''

元组的元素不可变(元组中的列表元素可以改变)

tp3 =(1, 3, ['a', 'b'], 'gh', '123')
tp3[2][0] = "abcc"
print(tp3)

'''
(1, 3, ['abcc', 'b'], 'gh', '123')

'''

(4)增删改查

  • 索引查

    index()

    tp=(1,2,3,"a","b",["aa","bb","cc","dd"])
    print(tp.index("a"))
    '''
    3
    
    '''
    
  • 切片查

不能

不能删除某个元素,但可以删除整个:

del tp
print(tp)
'''
Traceback (most recent call last):
  File "D:/pycharm_test/day03/03yuanzu.py", line 24, in <module>
    print(tp)
NameError: name 'tp' is not defined

'''

最大值

tp = ("a", "b", "c")
print(max(tp), min(tp))
'''
c a

'''

遍历

元素遍历

for i in tp:
    print(i)
'''
a
b
c
    
'''

索引遍历

for i in range(len(tp)):
    print(tp[i])

'''
a
b
c

'''

枚举遍历enumerate

for i in enumerate(tp):
    print(i)

'''
(0, 'a')
(1, 'b')
(2, 'c')

'''
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值