0
点赞
收藏
分享

微信扫一扫

05_python_元组

小安子啊 2022-02-20 阅读 35

元组

1、定义:元组类似于列表,但是在创建的时候,元组使用的是(),列表使用的是[ ]。当然也可以使用元组的内置方法tuple()进行创建。两者之间的主要区别是:元组是不变 的,而列表是可变的。

temp = ('hello','world',1,2)
temp1 = ('huan',"le",3,4)
# 元组的拼接,这个拼接是生成了一个新的元组,temp 和 temp1 都没有变
temp + temp1 
('hello', 'world', 1, 2, 'huan', 'le', 3, 4)
temp
('hello', 'world', 1, 2)
temp1
('huan', 'le', 3, 4)
# 元组的重复
temp1*3
('huan', 'le', 3, 4, 'huan', 'le', 3, 4, 'huan', 'le', 3, 4)
# 元组的切片
temp[1:3]
('world', 1)
# 注意点

# 1、圆括号和逗号
x1 = (1)      #这表示的是int型的 1
x1
1
type(x)
int
x = (1,)   #在 1 后面加一个逗号就成了元组类型了
type(x)
tuple
x
(1,)
# 元组的转换、方法和不可变性
temp2 = ('a','b','d','c')
T = list(temp2)
T
['a', 'b', 'd', 'c']
type(temp2)
tuple
type(T)
list
# sorted()方法可以用到元组上,而不用进行类型转换
sorted(temp2)
['a', 'b', 'c', 'd']
# 元组本身不能变,但是它的内容可以变

T= (1,[2,3],4)
print(T)
T[1][1] = 'huanle'
T

(1, [2, 3], 4)





(1, [2, 'huanle'], 4)

举报

相关推荐

0 条评论