从itertools.combinations中删除特定组合

And*_*rej 2 python

假设我们有一对元组,元组可以有不同的长度.我们称它们为元组,t1并且t2:

t1 = ('A', 'B', 'C')
t2 = ('d', 'e')
Run Code Online (Sandbox Code Playgroud)

现在我使用itertools计算来自两个元组的长度为2的所有组合:

import itertools
tuple(itertools.combinations(t1 + t2, 2))
Run Code Online (Sandbox Code Playgroud)

Itertools生成器产生所有可能的组合,但我只需要在元组之间发生的组合; 预期的产出是

(('A', 'd'), ('A', 'e'), ('B', 'd'), ('B', 'e'), ('C', 'd'), ('C', 'e'))
Run Code Online (Sandbox Code Playgroud)

我想知道删除不需要的组合的最佳方法是什么.

Kas*_*mvd 7

你需要itertools.product:

>>> t1 = ('A', 'B', 'C')
>>> t2 = ('d', 'e')
>>> from itertools import product
>>> 
>>> list(product(t1,t2))
[('A', 'd'), ('A', 'e'), ('B', 'd'), ('B', 'e'), ('C', 'd'), ('C', 'e')]
Run Code Online (Sandbox Code Playgroud)

如果你正在处理短元组,你可以通过列表理解来完成这项工作:

>>> [(i,j) for i in t1 for j in t2]
[('A', 'd'), ('A', 'e'), ('B', 'd'), ('B', 'e'), ('C', 'd'), ('C', 'e')]
Run Code Online (Sandbox Code Playgroud)