python - 在 Python 中打印两个列表的组合
问题描述
我要打印的是以下内容,为简单起见,在每个字符串中使用 2 个变量。我认为使用循环有问题,我对 Python 有点陌生。提前致谢!
com0 <-(a) with (1,)
com1 <-(a) with (2,)
com2 <-(a) with (1, 2)
com3 <-(b) with (1,)
com4 <-(b) with (2,)
com5 <-(b) with (1, 2)
com6 <-(a,b) with (1,)
com7 <-(a,b) with (2,)
com8 <-(a,b) with (1, 2)
这是我尝试过的:
import itertools
i = 0 #v1
j = 0 #v2
v1 = [1, 2]
v2 = ["a","b"]
while j < 2**len(v2):
for K in range(0, len(v2)+1):
while i < 2**len(v1):
for L in range(0, len(v1)+1):
for subset2 in itertools.combinations(v1, L):
for subset1 in itertools.combinations(v2, K):
print("com{0} <-{1} with {2}".format(i,subset1,subset2))
i+=1
j+=1
解决方案
from itertools 产生两个列表的product()
笛卡尔积。通过使用此功能,您可以避免所有循环:
import itertools
v1 = [1, 2]
v2 = ["a","b"]
combinations = list(itertools.product(v1, v2))
>> [(1, "a"), (1, "b"), (2, "a"), (2, "b")]
推荐阅读
- python - 使用 Selenium Python 下载嵌入式 SVG?
- python - 过滤具有最后修改时间的文件
- shell - 我输入了一个 shellscript 程序来生成一个数字表。我正在使用onworks(在线操作系统平台)
- android - Android 中的 Firebase 通知 (Kotlin)
- centos - 构建 HPL 的问题
- neural-network - 为什么 GAN 需要潜在空间噪声作为输入?
- python - 在TensorFlow中同时沿多个轴的Argmax
- reactjs - 类型错误:document.getElementById(...) 为空;使用 axios 做出反应
- deep-learning - Vnet 深度学习 3D 体积图像分割。如何处理大尺寸和不同尺寸的图像?
- database - 使用golang在postgres中从csv批量插入而不使用for循环