Python tuple()函数
tuple()
函数用于将一个可迭代对象转换为元组,其语法如下:
tuple(iterable)
其中:
iterable
参数是一个可迭代对象,例如列表、字符串等。
下面是一些示例,演示如何使用tuple()
函数:
# 将列表转换为元组
lst = [1, 2, 3]
tpl = tuple(lst)
print(tpl) # 输出 (1, 2, 3)
# 将字符串转换为元组
s = 'hello'
tpl = tuple(s)
print(tpl) # 输出 ('h', 'e', 'l', 'l', 'o')
# 将字典的键转换为元组
d = {'a': 1, 'b': 2, 'c': 3}
tpl = tuple(d.keys())
print(tpl) # 输出 ('a', 'b', 'c')