Python如何通过循环将两个列表元素全组合后赋值给新列表
你要实现的是两个列表的笛卡尔积存储为新列表,有三种常见实现方式:
方法1:沿用现有嵌套循环逻辑修改
你现在的写法只是直接打印了结果,只要初始化空列表,在循环内把组合追加到列表里即可:
list_1 = ['a','b','c'] list_2 = ['one', 'two', 'three'] new_list = [] for x in list_1: for y in list_2: # 如果你需要和打印输出一致的字符串格式 new_list.append(f"{x} {y}") # 如果你需要保留两个元素的独立结构,存为元组即可 # new_list.append((x, y))
方法2:列表推导式(更简洁的写法)
一行代码即可完成,逻辑和嵌套循环完全一致:
# 字符串格式 new_list = [f"{x} {y}" for x in list_1 for y in list_2] # 元组格式 new_list = [(x, y) for x in list_1 for y in list_2]
方法3:使用itertools.product(适合多列表、大数据量场景)
Python标准库自带的笛卡尔积计算工具,代码更简洁,处理长列表时效率更高:
from itertools import product list_1 = ['a','b','c'] list_2 = ['one', 'two', 'three'] # 得到元组组成的列表 new_list = list(product(list_1, list_2)) # 需要字符串格式的话再加一步格式转换 new_list = [f"{x} {y}" for x, y in product(list_1, list_2)]
内容的提问来源于stack exchange,提问作者rsq1725
相关产品推荐
相关产品推荐

