Python 中 N 元素增量元组
当需要创建“N”个元素递增元组时,可以使用生成器表达式和“元组”方法。
以下是同一展示 -
示例
N = 3 print("The value of 'N' has been initialized") print("The number of times it has to be repeated is : ") print(N) my_result = tuple((elem, ) * N for elem in range(1, 6)) print("The tuple sequence is : ") print(my_result)
输出
The value of 'N' has been initialized The number of times it has to be repeated is : 3 The tuple sequence is : ((1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4), (5, 5, 5))
解释
- 初始化“N”的值,并在控制台上显示。
- 将具有特定元素的元组,在给定范围内乘以“N”次,分配给变量。
- 生成此序列,并在控制台上显示为输出。
广告