Python tuple() 函数用法

2023-09-17 22:26:26

tuple()tuple 类的构造函数,用于创建空元组或将指定的可迭代对象转换为元组。

语法:

tuple(iterable)

参数:

可迭代:(可选)要转换为元组的序列或集合。

返回类型:

返回元组。

下面的示例将可迭代对象转换为元组。

tpl = tuple()
print("Empty tuple: ", tpl)
numbers_list = [1, 2, 3, 4, 5]
print("Converting list into tuple: ", tuple(numbers_list))
numbers_tuple = {1, 2, 3, 4, 5}
print("Converting set into tuple: ", tuple(numbers_tuple))
numbers_dict = {1:'one', 2:'two', 3:'three'}
print("Converting dictionary into tuple: ", tuple(numbers_dict))
greet = 'Hello'
print("Converting string into tuple: ", tuple(greet))

输出:

Empty tuple: ()
Converting list into tuple:  (1, 2, 3, 4, 5)
Converting set into tuple:  (1, 2, 3, 4, 5)
Converting dictionary into tuple:  (1, 2, 3)
Converting string into tuple:  ('H', 'e', 'l', 'l', 'o')