Python中的元组

1.元组的定义

(1)元组带了紧箍咒的列表,也可以存储任意数据类型
(2)元组特性

  • 没有增删改操作,不可变数据类型;虽然不能直接的对元组进行更改,但是如果元组中包含可变数据类型元素,可以根据元组中包含的元素,间接的对元组进行修改
    在这里插入图片描述
    在这里插入图片描述

  • 在定义元组时,如果元组中只有一个元素必须在元素后面加",",否则该元组类型非元组,而是该元素的类
    在这里插入图片描述
    (3)定义一个空元组tu=()
    (4)类型tuple
    在这里插入图片描述

2.元组的常用方法

2.1元组中元素的查找

(1)count 计数

   >>> tt
(1, 2, 5, 'python', [1, 2, 'hello', 'python'], 'python')
    >>> tt.count('python')
    2
    >>> tt.count(1)
    1
    >>> tt.count(2)
    1
    >>> tt.count(10)
    0

(2)index 索引查找,返回最小索引

>>> tt=t+('python',)
>>> tt
(1, 2, 5, 'python', [1, 2, 'hello', 'python'], 'python')
>>> tt.index('python')
3
>>> tt.index('python',4,10)

2.2元组的索引与切片

>>> t=(1,2,5,'python',[1,2,'hello','python'])
>>> t
(1, 2, 5, 'python', [1, 2, 'hello', 'python'])
>>> t[1]
2
>>> t[-1]
[1, 2, 'hello', 'python']
>>> t[1::]
(2, 5, 'python', [1, 2, 'hello', 'python'])
>>> t[:-1]
(1, 2, 5, 'python')
>>> t(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable
>>> t[1:]
(2, 5, 'python', [1, 2, 'hello', 'python'])
>>> t[::-1]
([1, 2, 'hello', 'python'], 'python', 5, 2, 1)
>>> t[:2]
(1, 2)

2.3元组的重复与连接

只有相同的数据结构类型才能进行连接,故只有元组才能与元组连接

>>> t * 2
(1, 2, 5, 'python', [1, 2, 'hello', 'python'], 1, 2, 5, 'python', [1, 2, 'hello', 'python'])
>>> t[-1]*3
[1, 2, 'hello', 'python', 1, 2, 'hello', 'python', 1, 2, 'hello', 'python']
>>> t[2:]*2
(5, 'python', [1, 2, 'hello', 'python'], 5, 'python', [1, 2, 'hello', 'python'])
>>> t+('hello')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "str") to tuple
>>> t+('hello',)
(1, 2, 5, 'python', [1, 2, 'hello', 'python'], 'hello')
>>> t+[1,2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "list") to tuple
>>>

2.4 元组中的成员操作符(in)

  >>> t
('haha', 20)
>>> 'haha ' in t
False
>>> 'haha' in t
True
>>> 20 in t
True
>>> 3 in t
False

2.5 元组的for循环

在这里插入图片描述

3.元组的应用场景

3.1 变量值交换

>>> a,b=(1,2)
>>> a
1
>>> b
2
>>> a,b=b,a
>>> a
2
>>> b
1

3.2多个变量的一次性赋值

>>> t=(1,2,3)
>>> a,b,c=t
>>> a
1
>>> b
2
>>> c
3

3.3 格式化输出应用

>>> t
(1, 2, 3)
>>> print("a=%d,b=%d,c=%d"%(1,2,3))
a=1,b=2,c=3
>>> print("a=%d,b=%d,c=%d"%(t))
a=1,b=2,c=3
>>>
>>> name='haha'
>>> age=20


>>> t=(name,age)
    >>> t
    ('haha', 20)
    >>> print("name:%s,age=%d"%(name,age))
    name:haha,age=20
    >>> print("name:%s,age=%d"%(t))
    name:haha,age=20
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值