小白教程

 找回密码
 立即注册

元组

发布者: 小白教程

元组用于将多个对象保持在一起。可以将它们视为类似于列表,但是没有列表类为您提供的广泛功能。元组的一个主要特征是它们像字符串一样不可变的,即您不能修改元组。

通过在可选的一对括号内指定用逗号分隔的项目来定义元组。

元组通常用于语句或用户定义的函数可以安全地假定值的集合(即所使用的值的元组)不会改变的情况下。

示例(另存为ds_using_tuple.py):

# I would recommend always using parentheses
# to indicate start and end of tuple
# even though parentheses are optional.
# Explicit is better than implicit.
zoo = ('python', 'elephant', 'penguin')
print('Number of animals in the zoo is', len(zoo))

new_zoo = 'monkey', 'camel', zoo    # parentheses not required but are a good idea
print('Number of cages in the new zoo is', len(new_zoo))
print('All animals in new zoo are', new_zoo)
print('Animals brought from old zoo are', new_zoo[2])
print('Last animal brought from old zoo is', new_zoo[2][2])
print('Number of animals in the new zoo is',
      len(new_zoo)-1+len(new_zoo[2]))

输出:

$ python ds_using_tuple.py
Number of animals in the zoo is 3
Number of cages in the new zoo is 3
All animals in new zoo are ('monkey', 'camel', ('python', 'elephant', 'penguin'))
Animals brought from old zoo are ('python', 'elephant', 'penguin')
Last animal brought from old zoo is penguin
Number of animals in the new zoo is 5

这个怎么运作

变量zoo引用项的元组。我们看到该len函数可用于获取元组的长度。这也表明一个元组也是一个序列

由于旧动物​​园关闭,我们现在将这些动物转移到新的动物园。因此,new_zoo元组中包含一些动物以及从旧动物园带来的动物。回到现实中,请注意,元组中的元组不会丢失其身份。

我们可以通过在一对方括号内指定项目的位置来访问元组中的项目,就像我们对列表所做的那样。这称为索引运算符。new_zoo通过指定来new_zoo[2]访问in中的第三项,并通过指定来访问new_zoo元组中第三项中的第三项new_zoo[2][2]一旦理解了惯用语,这将非常简单。

具有0或1项的元组

一个空的元组由一对空的括号构成,例如myempty = ()但是,具有单个项目的元组并不是那么简单。您必须在第一个(也是唯一的)项目之后使用逗号指定它,以便Python可以区分元组和表达式中围绕对象的一对括号,即,您必须指定singleton = (2 , )是否要包含该项目的元组2

给Perl程序员的注释

列表中的列表不会失去其标识,即列表未像Perl中那样变平。这同样适用于一个元组中的一个元组,或者一个列表中的一个元组,或者一个元组中的一个列表,等等。就Python而言,它们仅仅是使用另一个对象存储的对象。

上一篇:列表下一篇:字典

Archiver|手机版|小黑屋|小白教程 ( 粤ICP备20019910号 )

GMT+8, 2024-9-20 06:15 , Processed in 0.025437 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc. Template By 【未来科技】【 www.wekei.cn 】

返回顶部