Python – 所有可能的 N 組合元組


簡介

在 Python 中,元組是一種資料結構型別。元組由專案或元素組成,看起來更像列表。它包含在聲明後無法更改的元素。要返回元組的所有可能的組合,主要使用 itertool 庫。透過元組的迭代或重複過程是使用包含各種專案的迭代器物件完成的。為了返回元組中所有可能的組合,我們可以使用許多函式,如 combination()、chain()、product() 和連線方法。

所有可能的 N 組合元組

元組是一種資料結構,它包含在初始化後可互換的元素。元組通常被賦予一個值,並根據使用者的角度返回語句。在返回給定元組的所有可能組合的情況下,下面給出了使用不同方法的示例。

語法

combination(substr, N)

combination() 方法用於查詢字串可以選擇的方式的數量,並且要顯示的元素對作為 N 給出。

演算法

  • 步驟 1 − 根據函式的需要,將模組匯入程式碼。

  • 步驟 2 − 程式碼中使用的庫是 itertools 模組,用於使用 combination() 和 product() 函式。

  • 步驟 3 − 輸入字串宣告為 tuple_1 和 tuple_2,它們包含元組資料結構中的一組字串變數。

  • 步驟 4 − 宣告要列印的元素對的變數。

  • 步驟 5 − 使用 combination()、product() 方法和 append() 函式定義生成 'N' 可以列印的所有可能方式。

  • 步驟 6 − 將轉換後的值儲存在 combined_list 中。

  • 步驟 7 − print 語句根據 N 的值返回所有可能的組合。

方法

方法 1 − 使用 combination() 方法

方法 2 − 使用巢狀迴圈

方法 3 − 使用 product() 方法

方法 1:使用 combination() 方法顯示元組的 Python 程式

定義 Iter_object,並且還定義長度變數“N”,其值為 2。此程式碼使用 combination() 函式提取給定長度的所有可能的組合。組合後的元組儲存在一個名為 combined_tuple 的列表中。

示例

#itertools library is imported
import itertools 
#tuple_1 is initialized with list of values
tuple_1 = [3, 1, 7 ,5] 
#num variable is declared as 2
N=2 
#combinations() function is used to combine the list of values in two format
combined_tuples = list(itertools.combinations(tuple_1 ,N))
# It returns the tuples of the iter_object variable
print(combined_tuples)

輸出

[(3, 1), (3, 7), (3, 5), (1, 7), (1, 5), (7, 5)]

方法 2:使用巢狀迴圈顯示元組的 Python 程式

此方法不使用 itertool 模組,並使用巢狀 for 迴圈迭代元組的值。兩個元組使用變數值列表初始化,並且還定義了一個空列表。使用 append() 函式,我們可以將兩個元組組合在一起,並建立一個包含元素對的新元組。

示例

#tuple_1 and tuple_2 is initialized with a list of values
tuple_1 = (5, 7)
tuple_2 = (6, 1)
#empty list is initialized
combined_list = []
# nested for loop is used to iterate through the tuples
for one in tuple_1:
   for two in tuple_2:
      combined_list.append((one,two))

# It returns the tuples of the combined_list variable
print("All possible combinations of the tuple are:",combined_list)

輸出

All possible combinations of the tuple are: [(5, 6), (5, 1), (7, 6), (7, 1)]

方法 3:使用 product() 方法顯示元組的 Python 程式

迭代元組所需的庫是 itertools。兩個元組使用變數值列表初始化。使用 product() 函式可以輕鬆地組合兩個元組,該函式對項進行笛卡爾積,並使用 print 語句返回所有可能的值。

示例

#itertools library is imported
import itertools
#tuple_1 and tuple_2 is initialized with a list of values
tuple_1 = (5, 7, 1, 4, 1)
tuple_2 = (6, 8, 2, 0, 2)
#product() function is used to get the combined tuple values
combined_list = list(itertools.product(tuple_1, tuple_2))
# It returns the tuples of the combined_list variable
print("All possible combinations of the tuple are:",combined_list)

輸出

All possible combinations of the tuple are: [(5, 6), (5, 8), (5, 2), (5, 0), (5, 2), (7, 6), (7, 8), (7, 2), (7, 0), (7, 2), (1, 6), (1, 8), (1, 2), (1, 0), (1, 2), (4, 6), (4, 8), (4, 2), (4, 0), (4, 2), (1, 6), (1, 8), (1, 2), (1, 0), (1, 2)]

結論

在 Python 語言中,使用括號“()”來指示您已聲明瞭一個元組。這些括號內的元素可以使用元素來定義初始化為元組。元組的優點是它遵循定義元素的特定順序。

更新於: 2023-08-25

501 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.