gpt4 book ai didi

python - 从 itertools.combinations 中删除特定组合

转载 作者:行者123 更新时间:2023-11-28 20:42:17 25 4
gpt4 key购买 nike

假设我们有一对元组,其中元组的长度可以不同。我们称它们为元组 t1t2:

t1 = ('A', 'B', 'C')
t2 = ('d', 'e')

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

import itertools
tuple(itertools.combinations(t1 + t2, 2))

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

(('A', 'd'), ('A', 'e'), ('B', 'd'), ('B', 'e'), ('C', 'd'), ('C', 'e'))

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

最佳答案

你需要 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')]

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

>>> [(i,j) for i in t1 for j in t2]
[('A', 'd'), ('A', 'e'), ('B', 'd'), ('B', 'e'), ('C', 'd'), ('C', 'e')]

关于python - 从 itertools.combinations 中删除特定组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31131526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com