Python – 所有可能的N个组合元组

Python – 所有可能的N个组合元组

介绍

在Python中,元组是一种数据结构之一。元组由项或元素组成,类似于列表。声明后无法更改其元素。为了返回元组的所有可能的组合,通常会使用itertools库。通过迭代器对象,可以对元组进行迭代或重复处理。为了返回元组中所有可能的组合,我们可以使用combination()、chain()、product()和concatenation方法等多个函数。

所有可能的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模块,而是使用嵌套循环来遍历元组的值。两个元组使用可变值列表进行初始化,同时定义了一个空列表。使用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)]

方法三:使用product()方法显示元组的Python程序

迭代元组所需的库是itertools。两个元组被初始化为一个变量列表的值。通过使用product()函数和打印语句返回所有可能的值,将两个元组的合并过程变得简单。

示例

#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语言中,用括号”()”表示已经声明了一个元组。在这些括号内的元素可以用元组初始化的元素进行定义。元组的优点是它遵循元素定义的特定顺序。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程