tuple元组(戴上枷锁的列表)
1 元组的创建 tuple = (2,4,1,54,0) 重点在于逗号
2 元组的访问 tuple1[0] 访问tuple1的第一个元素
3 元组的分片 slice tuple1[start:stop]
1 元组的创建 tuple = (2,4,1,54,0) 重点在于逗号
2 元组的访问 tuple1[0] 访问tuple1的第一个元素
3 元组的分片 slice tuple1[start:stop]
元组不可修改
标志为 ,
tuple2 = 5,
tuple3 = () 为空元组
标志为 ,
tuple2 = 5,
tuple3 = () 为空元组
对元组的操作
利用切片slice间接对元组进行添加、删减
>>> temp = (1,2,4,5,6)
>>> temp = temp[:2] + (3,) + temp[2:]
>>> temp
(1, 2, 3, 4, 5, 6)
1.序列解包
The statement t = 12345, 54321, 'hello!' is an example of tuple packing: the values 12345, 54321 and 'hello!' are packed together in a tuple. The reverse operation is also possible:
x,y,z = t
x,y,z = t
This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.
这被称为适当的序列解包,并适用于右侧的任何序列。序列解包要求等号的左边有多个变量,因为序列中有元素。请注意,多重赋值实际上是元组打包和序列解包的组合。
可以使用序列解包功能对多个变量同时进行赋值:
>>> x,y,z = 1,2,3
>>> x
1
>>> y
2
>>> z
3
>>>
>>> v_tuple=(False,2.5,'exp')
>>> x,y,z=v_tuple
>>> x
False
>>> y
2.5
>>> z
'exp'
>>>
#序列解包也可以应用于字典和列表,但是对字典使用时,默认对‘键’进行操作。可以使用.values() .items()
>>> a = [1,2,3]
>>> b,c,d = a
>>> c
2
>>>
>>> s={'a':50,'b':'cdsad','k':'$$'}
>>> b,c,d=s.values()
>>> c
'cdsad'
>>>
>>> s={'a':50,'b':'cdsad','k':'$$'}
>>> b,c,d=s.items()
>>> d
('k', '$$')
>>>
>>> keys = ['adc','uzi','pdd','faker']
>>> values = [6,7,3,7]
>>> for i,j in zip(keys,values):
print (i,j)
adc 6
uzi 7
pdd 3
faker 7
>>>
2.生成器推导式
类似于列表推导式,但与之不同的是,生成器推导式的结果是一个生成器对象,而不是列表,也不是元组。使用生成器对象的元素时,可以根据需要将其转化为列表或元组,也可以使用生成器对象的__next__()方法进行遍历,或者直接将其作为迭代器对象来使用。但不管用哪种方法访问其元素,当所有元素访问结束以后,如果需要重新访问其中的元素,必须重新创建该生成器对象。
类似于列表推导式,但与之不同的是,生成器推导式的结果是一个生成器对象,而不是列表,也不是元组。使用生成器对象的元素时,可以根据需要将其转化为列表或元组,也可以使用生成器对象的__next__()方法进行遍历,或者直接将其作为迭代器对象来使用。但不管用哪种方法访问其元素,当所有元素访问结束以后,如果需要重新访问其中的元素,必须重新创建该生成器对象。
>>> g = ((i+2)**2 for i in range(10))
>>> g
<generator object <genexpr> at 0x000001EA21A89990>
>>> tuple(g) #转化为元组
(4, 9, 16, 25, 36, 49, 64, 81, 100, 121)
>>> tuple(g)
() #元素已经遍历结束
>>>
>>> g = ((i+2)**2 for i in range(10))
>>> g.__next__() #单步迭代
4
>>> g.__next__()
9
>>> g.__next__()
16
>>>