在 Python 中将元组列表内的元组组合起来
pythonserver side programmingprogramming更新于 2026/1/13 3:24:17
对于数据分析,我们有时会采用 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) 的迭代器,它创建传递给它的参数的笛卡尔积。在此示例中,我们设计了 for 循环来遍历元组的每个元素并与元组中的非列表元素形成一对。
示例
from itertools import product
Alist = [([2, 8, 9], 'Mon'), ([7, 5, 6], 'Wed')]
# 给定元组列表
print("List of tuples : \n",Alist)
# Combine tuples in list of tuples
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')]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

