元组()


关于元组

元组对象的本质是一个有序的、可迭代、可切片、不可变的序列,且内部元素支持任意对象。但通常为可哈希对象。

不能改变元祖,但可以改变元祖里的可变对象;


元组 & 列表

  • 元组的元素不能修改;列表可以修改;

  • 元组使用小括号 ( ) , 列表使用方括号 [ ]


元组 & 字符串

字符串可以看作一种特殊的元组;

元祖 和 字符串 都不能改变,但可以改变元祖里的可变对象;


创建

>>> tup1 = ('Google', 'Runoob', 1997, 2000)
>>> tup2 = (1, 2, 3, 4, 5 )
>>> tup3 = "a", "b", "c", "d"   #  不需要括号也可以 任何对象,中间有逗号,都会被看作元祖。

# 查看类型
>>> type(tup3)
<class 'tuple'>

# 空元组
>>> tup1 = ()

# 元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用:
>>> tup1 = (50)
>>> type(tup1)     # 不加逗号,类型为整型
<class 'int'>

>>> tup1 = (50,)
>>> type(tup1)     # 加上逗号,类型为元组
<class 'tuple'>
  • 不可变对象的优势在于高性能(固定内存段),线程安全(无需锁)和可哈希(多值Key的字典)等,典型的如数字,字符串,元祖

# 查看tuple类型的定义
>>> help(tuple)

# 查看tuple类型的属性和方法
>>> dir(tuple)

赋值

>>> x,y = 1,2
>>> x,y
(1, 2)

>>> x,y = (1,2)
>>> x,y
(1, 2)

>>> z = (3,4)
>>> x,y = z
>>> x,y
(3, 4)
for (x,y) in ((1, 2),(3, 4)):
    print(x)
    print(x,y)
    print((x,y))
    print('\n')
    
'''
1
1 2
(1, 2)


3
3 4
(3, 4)
'''

访问

索引

tup1 = ('Google', 'Runoob', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )

# 1.正向单索引
tup1[0] # Google

# 2.负向单索引
tup1[-1] # 2000

# 3.切片索引
tup2[1:5] # (2, 3, 4, 5)


# 4.无限索引
# 如果第一个索引是0,可以省略:
tup2[:3]  # (1, 2, 3)

# 倒数切片
tup2[-2:] # (6, 7)

# 隔位取
tup2[::2]
# (1, 3, 5, 7)

tup2[::3]
# (1, 4, 7)

tup2[-3:-1]
# (5, 6)

修改元组

元组中的元素值是不允许修改的,但我们可以对元组进行连接组合,如下实例:

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

以上实例输出结果:

(12, 34.56, 'abc', 'xyz')


删除元组

元组中的元素值是不允许删除的,但我们可以使用 del 语句来删除整个元组,如下实例:

#!/usr/bin/python3
 
tup = ('Google', 'Runoob', 1997, 2000)
 
print(tup)
del tup
print ("删除后的元组 tup : ")

print (tup) # 删除后变量不存在
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-12-95b80b2375ef> in <module>
----> 1 tup

NameError: name 'tup' is not defined

元组运算符

运算符:+, *, in, not in

与字符串一样,元组之间可以使用 + 号和 * 号进行运算。这就意味着他们可以组合和复制,运算后会生成一个新的元组。

>>> (1, 2, 3) + (4, 5, 6)
(1, 2, 3, 4, 5, 6)

>>> ('Hi!',) * 4
('Hi!', 'Hi!', 'Hi!', 'Hi!')

>>> 3 in (1, 2, 3)
True

>>> for x in (1, 2, 3): print (x,)
1 2 3

内置函数

len、max,min,tuple

>>> len((1, 2, 3))  
3

>>> max((1, 2, 3))  
3

>>> min((1, 2, 3))  
1

# 将可迭代系列转换为元组。
>>> tuple(['a', 'b', 'c', 'd'])
('a', 'b', 'c', 'd')

>>> tuple('abcd')
('a', 'b', 'c', 'd')

>>> dir(tuple)
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rmul__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'count',
 'index']

****

>>> help(tuple)
Help on class tuple in module builtins:

class tuple(object)
 |  tuple(iterable=(), /)
 |  
 |  Built-in immutable sequence.
 |  
 |  If no argument is given, the constructor returns an empty tuple.
 |  If iterable is specified the tuple is initialized from iterable's items.
 |  
 |  If the argument is a tuple, the return value is the same object.
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(self, key, /)
 |      Return self[key].
 |  
 |  __getnewargs__(self, /)
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /)
 |      Return hash(self).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __rmul__(self, value, /)
 |      Return value*self.
 |  
 |  count(self, value, /)
 |      Return number of occurrences of value.
 |  
 |  index(self, value, start=0, stop=9223372036854775807, /)
 |      Return first index of value.
 |      
 |      Raises ValueError if the value is not present.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.

相关资料

菜鸟 元组: https://www.runoob.com/python3/python3-tuple.html


posted @ 2021-02-04 11:26  小然-  阅读(230)  评论(0编辑  收藏  举报