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”次,分配給變數。
  • 生成此序列,並在控制檯上顯示為輸出。

更新時間:2021 年 3 月 11 日

170 次瀏覽

職業 道路上一鳴驚人

完成課程獲得認證

開始
廣告
© . All rights reserved.