Python 中 2 個元組的所有成對組合


當需要在兩個元組之間找出所有成對組合時,可以使用列表解析。

以下是對其進行演示的示例 −

示例

 即時演示

from itertools import product
N = 2
print("The value of N has been initialized to ")
print(N)
my_result = [ele for ele in product(range(1, N + 1), repeat = N)]

print("All tuple combinations until 2 are : " )
print(my_result)

輸出

The value of N has been initialized to
2
All tuple combinations until 2 are :
[(1, 1), (1, 2), (2, 1), (2, 2)]

說明

  • 匯入所需的包。

  • 設定 N 的值並將其顯示在控制檯上。

  • 列表解析用於遍歷 N 之前的各個值,並對它們進行增加。

  • 將其賦值給一個變數。

  • 將其顯示為控制檯輸出。

更新日期:2021 年 4 月 17 日

208 次瀏覽

開啟您的職業生涯之旅

完成課程獲取認證

開始學習
廣告