Python Tuple tuple() 方法用于将项目列表转换为 Tuples。
元组是 python 对象的集合,这些对象由逗号分隔,这些逗号是有序且不可变的。元组是序列,就像列表一样。元组和列表之间的区别在于:元组不能更改,这与列表不同,元组使用括号,而列表使用方括号。
语法
以下是 Python Tuple tuple() 方法的语法 -
tuple(seq)
参数
- seq − 这是一个要转换为 Tuples 的序列。
返回值
此方法返回此 Tuples。
例以下示例显示了 Python Tuple tuple() 方法的用法。这里正在创建一个列表 'aList',它由字符串作为其元素组成。然后使用 tuple() 方法将此列表转换为 Tuples。
aList = ['xyz', 'zara', 'abc']
aTuple = tuple(aList)
print ("Tuple elements : ", aTuple)
当我们运行上述程序时,它会产生以下结果——
Tuple elements : ('xyz', 'zara', 'abc')
例
在这里,我们将创建一个字典 'dict1'。然后,这个字典作为参数传递给 tuple() 方法。此后,我们检索字典的元组。
# iterable dictionary
dict1 = {'Name': 'Rahul', 'Hobby': 'Singing', 'RollNo': 45}
# using tuple() method
res = tuple(dict1)
# printing the result
print("dictionary to tuple:", res)
在执行上述代码时,我们得到以下输出 -
dictionary to tuple: ('Name', 'Hobby', 'RollNo')
例
现在,我们将创建一个字符串。然后,此字符串将作为参数传递给 tuple() 方法。此后,我们检索字符串的元组。
# iterable string
string = "QikepuCom Point";
# using tuple() method
res = tuple(string)
# printing the result
print("converted string to tuple:", res)
以下是上述代码的输出 -
converted string to tuple: ('Q', 'i', 'k', 'e', 'p', 'u', 'C', 'o', 'm', ' ', 'P', 'o', 'i', 'n', 't')
例
如果在此方法中传递空 Tuples,则 tuple() 方法不会引发任何错误。它返回一个空元组。
# empty tuple
tup = tuple()
print("Output:", tup)
上述代码的输出如下 -
empty tuple: ()
例
如果未传递可迭代对象,则 tuple() 方法会引发 TypeError。下面给出的代码解释了它。
#a non-iterable is passed as an argument
tup = tuple(87)
# printing the result
print('Output:', tup)
我们得到上述代码的输出,如下所示 -
Traceback (most recent call last):
File "C:\Users\Lenovo\Desktop\untitled.py", line 2, in <module>
tup = tuple(87)
TypeError: 'int' object is not iterable
File "C:\Users\Lenovo\Desktop\untitled.py", line 2, in <module>
tup = tuple(87)
TypeError: 'int' object is not iterable