首页 文章资讯内容详情

在Python中合并元组列表中的元组

2026-06-04 1 花语

为了进行数据分析,有时我们会结合使用python中可用的数据结构。列表可以包含元组作为其元素。在本文中,我们将看到如何将一个元组的每个元素与另一个给定元素组合在一起,并产生一个列表元组组合。

带for循环

在下面的方法中,我们创建for循环,该循环将通过获取元组的每个元素并遍历列表中的元素来创建一对元素。

示例

Alist = [([2, 8, 9], Mon), ([7, 5, 6], Wed)] #给定元组列表 print("List of tuples : \n",Alist) #合并元组列表中的元组 res = [(t1, t2) for i, t2 in Alist for t1 in i] #打印结果 print("The list tuple combination : \n" ,res)

输出结果

运行上面的代码给我们以下结果-

List of tuples : [([2, 8, 9], Mon), ([7, 5, 6], Wed)] The list tuple combination : [(2, Mon), (8, Mon), (9, Mon), (7, Wed), (5, Wed), (6, Wed)]

与product迭代器

itertools模块具有名为product的迭代器,该迭代器创建传递给其的参数的笛卡尔积。在此示例中,我们设计了循环,以遍历元组的每个元素,并与元组中的非列表元素形成一对。

示例

from itertools import product Alist = [([2, 8, 9], Mon), ([7, 5, 6], Wed)] #给定的元组列表 print("List of tuples : \n",Alist) #合并元组列表中的元组 res = [x for i, j in Alist for x in product(i, [j])] #打印结果 print("The list tuple combination : \n" ,res)

输出结果

运行上面的代码给我们以下结果-

List of tuples : [([2, 8, 9], Mon), ([7, 5, 6], Wed)] The list tuple combination : [(2, Mon), (8, Mon), (9, Mon), (7, Wed), (5, Wed), (6, Wed)]