Python Tuples(元组)是类似于列表的一种集合,元组中存储的值可以是任何类型,并且它们通过整数索引。这篇文章,我们将深入地分析 Python Tuples(元组)。
创建元组
在 Python 中,元组通过放置由“逗号”分隔的值序列来创建,可以使用或不使用括号来分组数据序列。
注意:不使用括号创建 Python元组被称为元组打包(Tuple Packing)。
下面通过一个示例展示在元组中添加元素:
# 创建一个空元组
tuple1 = ()
print("初始空元组: ")
print(tuple1)
# 使用字符串创建元组
tuple1 = ('Hello', 'World')
print("\n使用字符串创建元组: ")
print(tuple1)
# 使用列表创建元组
list1 = [1, 2, 4, 5, 6]
print("\n使用列表创建元组: ")
print(tuple(list1))
# 使用内置函数创建元组
tuple1 = tuple('Python')
print("\n使用内置函数创建元组: ")
print(tuple1)
输出:
初始空元组:
()
使用字符串创建元组:
('Hello', 'World')
使用列表创建元组:
(1, 2, 4, 5, 6)
使用内置函数创建元组:
('P', 'y', 't', 'h', 'o', 'n')
使用混合数据类型创建元组
Python元组可以包含任意数量的元素和任意数据类型(如字符串、整数、列表等)。元组也可以只包含一个元素,但这有点棘手。在括号中有一个元素是不够的,必须有一个尾随的“逗号”才能使其成为元组。
tuple1 = (5,)
print("\n使用混合数据类型创建元组: ")
print(tuple1)
# 使用混合数据类型创建元组
tuple1 = (5, 'Welcome', 7, 'Python')
print("\n使用混合数据类型创建元组: ")
print(tuple1)
# 使用嵌套元组创建元组
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'tuple')
tuple3 = (tuple1, tuple2)
print("\n使用嵌套元组创建元组: ")
print(tuple3)
# 使用重复创建元组
tuple1 = ('Hello',) * 3
print("\n使用重复创建元组: ")
print(tuple1)
# 使用循环创建元组
tuple1 = ('Hello')
n = 5
print("\n使用循环创建元组")
for i in range(int(n)):
tuple1 = (tuple1,)
print(tuple1)
输出:
使用