1.1.3 python基本数据类型之元组

点击跳转Python学习笔记总目录

一,元组tuple

Python 的元组与列表类似,不同之处在于元组的元素不能修改

1,元组创建

tup1 = ('Google', 'Runoob', 1997, 2000)

创建空元组

tup = ()

元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用:

tup1 = (50)
type(tup1)     # 不加逗号,类型为整型
输出
<class 'int'>
 
tup1 = (50,)
type(tup1)     # 加上逗号,类型为元组
输出
<class 'tuple'>

2,访问元组

tup1 = ('Google', 'Runoob', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
 
print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])
输出:
tup1[0]:  Google
tup2[1:5]:  (2, 3, 4, 5)

3,修改元组

tup1 = (12, 34.56);
tup2 = ('abc', 'xyz')
 
# 以下修改元组元素操作是非法的。
# tup1[0] = 100
 
# 创建一个新的元组
tup3 = tup1 + tup2;
print (tup3)
输出
(12, 34.56, 'abc', 'xyz')

4,删除元组

tup = ('Google', 'Runoob', 1997, 2000)
 
print (tup)
del tup;
print ("删除后的元组 tup : ")
print (tup)

输出
删除后的元组 tup : 
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print (tup)
NameError: name 'tup' is not defined

5,元组运算

len((1, 2, 3)) 计算元素个数

tup = (1,2,3)
n = len(tup)
print(n)
输出
3

(1, 2, 3) + (4, 5, 6) 连接

tup = (1, 2, 3) + (4, 5, 6)
print(tup)
输出
(1, 2, 3, 4, 5, 6)

(‘Hi!’,) * 4 复制

tup = ('Hi!',) * 4
print(tup)
输出
('Hi!', 'Hi!', 'Hi!', 'Hi!')

3 in (1, 2, 3) 元素是否存在

status = 3 in (1, 2, 3)
print(status)	
输出
True

for x in (1, 2, 3): print (x,) 1 2 3 迭代

for x in (1, 2, 3): print (x,)
输出
1
2
3

6,元组索引,截取

L = ('Google', 'Taobao', 'python')
item = L[1]
print(item)
输出
taobao
#######################################
item = L[-1]
print(item)
输出
python
#######################################
item = L[0:2]
print(item)
输出
('Google', 'Taobao')

7,内置函数

1, len(tuple)
计算元组元素个数。

tup = ('Google', 'Taobao', 'python')
n = len(tup)
print(n)
输出
3

2 max(tuple)
返回元组中元素最大值。

tup = (1, 2, 3)
n = max(tup)
print(n)
输出
3

3 min(tuple)
返回元组中元素最小值。

tup = (1, 2, 3)
n = max(tup)
print(n)
输出
1

4 tuple(seq)
将列表转换为元组。

tup = tuple([1,2,3])
print(tup)
输出
(1, 2, 3)

猜你喜欢

转载自blog.csdn.net/weixin_39726347/article/details/86546241
今日推荐