Python中的元组
元组是由逗号分隔的Python对象的集合。在某些方面,元组在索引、嵌套对象和重复方面类似于列表,但元组是不可变的,不像列表是可变的。
创建元组
# An empty tuple
empty_tuple = ()
print (empty_tuple)
输出:
()
# Creating non-empty tuples
# One way of creation
tup = 'python', 'geeks'
print(tup)
# Another for doing the same
tup = ('python', 'geeks')
print(tup)
输出
('python', 'geeks')
('python', 'geeks')
注意:如果您使用单个元素生成元组,请确保在元素后添加逗号。
元组的连接
# Code for concatenating 2 tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'geek')
# Concatenating above two
print(tuple1 + tuple2)
输出:
(0, 1, 2, 3, 'python', 'geek')
元组的嵌套
# Code for creating nested tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'geek')
tuple3 = (tuple1, tuple2)
print(tuple3)
输出 :
((0, 1, 2, 3), ('python', 'geek'))
元组中的重复
# Code to create a tuple with repetition
tuple3 = ('python',)*3
print(tuple3)
输出
('python', 'python', 'python')
试试上面没有逗号并检查。您将得到 tuple3 作为字符串'pythonpythonpython'。
不可变元组
#code to test that tuples are immutable
tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)
输出
Traceback (most recent call last):
File "e0eaddff843a8695575daec34506f126.py", line 3, in
tuple1[0]=4
TypeError: 'tuple' object does not support item assignment
在元组中切片
# code to test slicing
tuple1 = (0 ,1, 2, 3)
print(tuple1[1:])
print(tuple1[::-1])
print(tuple1[2:4])
输出
(1, 2, 3)
(3, 2, 1, 0)
(2, 3)
删除元组
# Code for deleting a tuple
tuple3 = ( 0, 1)
del tuple3
print(tuple3)
错误:
Traceback (most recent call last):
File "d92694727db1dc9118a5250bf04dafbd.py", line 6, in
print(tuple3)
NameError: name 'tuple3' is not defined
输出:
(0, 1)
查找元组的长度
# Code for printing the length of a tuple
tuple2 = ('python', 'geek')
print(len(tuple2))
输出
2
将列表转换为元组
# Code for converting a list and a string into a tuple
list1 = [0, 1, 2]
print(tuple(list1))
print(tuple('python')) # string 'python'
输出
(0, 1, 2)
('p', 'y', 't', 'h', 'o', 'n')
接受一个参数,它可以是一个列表、字符串、集合甚至是一个字典(只有键被视为元素)并将它们转换为元组。
循环中的元组
#python code for creating tuples in a loop
tup = ('geek',)
n = 5 #Number of time loop runs
for i in range(int(n)):
tup = (tup,)
print(tup)
输出 :
(('geek',),)
((('geek',),),)
(((('geek',),),),)
((((('geek',),),),),)
(((((('geek',),),),),),)
使用 cmp()、max()、min()
# A python program to demonstrate the use of
# cmp(), max(), min()
tuple1 = ('python', 'geek')
tuple2 = ('coder', 1)
if (cmp(tuple1, tuple2) != 0):
# cmp() returns 0 if matched, 1 when not tuple1
# is longer and -1 when tuple1 is shorter
print('Not the same')
else:
print('Same')
print ('Maximum element in tuples 1,2: ' +
str(max(tuple1)) + ',' +
str(max(tuple2)))
print ('Minimum element in tuples 1,2: ' +
str(min(tuple1)) + ',' + str(min(tuple2)))
输出
Not the same
Maximum element in tuples 1,2: python,coder
Minimum element in tuples 1,2: geek,1
注意:max() 和 min() 检查基于 ASCII 值。如果元组中有两个字符串,则检查字符串中的第一个不同字符。