对于Python中的元组(Tuple)的理解

1.对于列表和字符串有许多共同的操作属性,例如切片和索引,他们都属于序列操作类型。但是,元组也属于序列操作的一种类型,它却与列表有许多不同之处。

1.实例
t = 12345, 54321, 'hello'
#输出结果
t[0] 输出结果
    12345
t    输出结果
(12345, 54321, 'hello') #说明t的数据类型是元组类型
print(type(t))输出结果为:
<class 'tuple'>

2.实例

u = t, 'world'
print(u) #输出结果为
((12345, 54321, 'hello'), 'world') #说明元组里面也包含着元组,与列表有相似之处
print(u[0]) #输出结果为
(12345, 54321, 'hello')
u[1] = 'Stranger' #输出结果为
#报错
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    u[1] = 'Stranger'
TypeError: 'tuple' object does not support item assignment

3.实例
#元组里面包含着列表
s = ([1, 2, 3],['orange', 'apple'])
print(s) #输出结果为
([1, 2, 3], ['orange', 'apple'])

4.实例
x, y = s
print(x) #输出结果为:
[1, 2, 3]
print(y) #输出结果
['orange', 'apple']


正如上面三个实例所看,元组的输出结果总是被括号包括着。

猜你喜欢

转载自blog.csdn.net/qq_34138155/article/details/81162663
今日推荐