python基础08_元组_tuple

关注有惊喜

在这里插入图片描述

元组-tuple

元组可以看成是一个不可更改的list

元组创建

In [32]:

创建空元组

t = ()
print(type(t))

创建一个只有一个值的元组

t = (1,)
print(type(t))
print(t)

t = 1,
print(type(t))
print(t)

创建多个值的元组

t = (1,2,3,4,5)
print(type(t))
print(t)

t = 1,2,3,4,5
print(type(t))
print(t)

使用其他结构创建

l = [1,2,3,4,5]
t = tuple(l)
print(type(t))
print(t)
<class ‘tuple’>
<class ‘tuple’>
(1,)
<class ‘tuple’>
(1,)
<class ‘tuple’>
(1, 2, 3, 4, 5)
<class ‘tuple’>
(1, 2, 3, 4, 5)
<class ‘tuple’>
(1, 2, 3, 4, 5)
元组的特性
是序列表,有序
元组数据值可以访问,不能修改,不能修改,不能修改
元组数据可以是任意类型
总之,list所有特性,除了可修改外,元组都具有
也就意味着,list具有的一些操作,比如索引,分片,序列相加,相乘,成员资格操作等,一模一样
In [33]:

索引操作

t = (1,2,3,4,5)
print(t[4])
5
In [34]:

超标错误

print(t[12])

IndexError Traceback (most recent call last)
in ()
----> 1 print(t[12])

IndexError: tuple index out of range
In [37]:
t = (1,2,3,4,5,6)
t1 = t[1::2]
print(id(t))
print(id(t1))
print(t1)

切片可以超标

t2 = t[2:100]
print(t2)
140249409775272
140249408604272
(2, 4, 6)
(3, 4, 5, 6)
In [46]:

序列相加

t1 = (1,2,3)
t2 = (5,6,7)

传址操作

print(t1)
print(id(t1))
t1 = t1 + t2
print(t1)
print(id(t1))

以上操作,类似于

t1 = (1,2,3)
t1 = (2,3,4)

tuple 的不可修改,指的是内容的不可修改

修改tuple内容会导致报错

t1[1] = 100
(1, 2, 3)
140249408457464
(1, 2, 3, 5, 6, 7)
140249409775368

TypeError Traceback (most recent call last)
in ()
16 # tuple 的不可修改,指的是内容的不可修改
17 # 修改tuple内容会导致报错
—> 18 t1[1] = 100

TypeError: ‘tuple’ object does not support item assignment
In [48]:

元组相乘

t = (1,2,3)
t = t * 3
print(t)
(1, 2, 3, 1, 2, 3, 1, 2, 3)
In [50]:

成员检测

t = (1,2,3)
if 2 in t:
print(“YES”)
else:
print(“NO”)
YES
In [54]:

元组遍历,一般采用for

1. 单层元组遍历

t = (1,2,3,“wangxiaojing”, “i”, “love”)
for i in t:
print(i, end=" ")
1 2 3 wangxiaojing i love
In [56]:

2. 双层元组的遍历

t = ((1,2,3), (2,3,4),(“i”, “love”, “wangxiaojing”))

对以上元组的遍历,可以如下

1.

for i in t:
print(i)

for k,m,n in t:
print(k,’–’,m,’–’,n)
(1, 2, 3)
(2, 3, 4)
(‘i’, ‘love’, ‘wangxiaojing’)
1 – 2 – 3
2 – 3 – 4
i – love – wangxiaojing

关于元组的函数
以下看代码
以下函数,对list基本适用
In [5]:

len: 获取元组的长度

t = (1,2,3,4,5)
len(t)
Out[5]:
5
In [7]:

max, min:最大最小值

如果,列表或元组中有多个最大最小值,则实际打印出哪个

print(max(t))
print(min(t))
5
1
In [12]:

tuple:转化或创建元组

l = [1,2,3,4,5]
t = tuple(l)
print(t)

t = tuple()
print(t)
(1, 2, 3, 4, 5)
()
元组的函数
基本跟list通用
In [16]:

count: 计算制定数据出现的次数

t = (2,1,2,3,45,1,1,2,)

print(t.count(2))

index:求制定元素在元组中的索引位置

print(t.index(45))

如果需要查找的数字是多个,则返回第一个

print(t.index(1))
3
4
1
元组变量交换法
两个变量交换值
In [20]:

两个变量交换值

a = 1
b = 3

print(a)
print(b)
print("*" * 20)

java程序员会这么写:

c = a
a = b
b = c
print(a)
print(b)

print("*" * 20)

python的写法

a,b = b,a
print(a)
print(b)
1
3


3
1


1
3

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值