Python中的元组数据类型


元组是另一种序列数据类型,它类似于列表。元组由多个逗号分隔的值组成。然而,与列表不同,元组用圆括号括起来。

示例

列表和元组之间的主要区别在于:列表用方括号 ( [ ] ) 括起来,其元素和大小都可以更改,而元组用圆括号 ( ( ) ) 括起来,并且不能更新。可以将元组视为只读列表。例如 −

 实际演示

#!/usr/bin/python
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print tuple # Prints complete list
print tuple[0] # Prints first element of the list
print tuple[1:3] # Prints elements starting from 2nd till 3rd
print tuple[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints list two times
print tuple + tinytuple # Prints concatenated lists

输出

产生以下结果 −

('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

以下代码对于元组无效,因为我们尝试更新元组,这是不允许的。对于列表,也可能出现类似的情况 −

#!/usr/bin/python
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list

更新时间:2020 年 1 月 24 日

839 次浏览

开启你的 事业

通过完成课程获得认证

开始学习
广告
© . All rights reserved.