在 Python 中测试所有组合
我有两组选项:
optionList1 = [a1,a2,a3,...,an]
optionList2 = [b1,b2,b3,...,bn]
选项列表中的元素数量不一定相等,我必须从第一个选项列表中选择两次。如何确保我已尝试了第一个列表中的 2 个选项和第二个列表中的一个选项的每种组合。下面是一个选择集示例...
selectedOptions = [an1,an2,bn]
I have two sets of options:
optionList1 = [a1,a2,a3,...,an]
optionList2 = [b1,b2,b3,...,bn]
The number of elements in the optionlists are not necessarily equal and I have to choose from the first optionlist twice. How do I ensure that I have tried every combination of 2 options from the first list and one from the second list. An example selection set below...
selectedOptions = [an1,an2,bn]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
假设您不希望第一个列表中出现重复项,则合并来自
itertools
的product
和permutations
:Combine
product
andpermutations
fromitertools
assuming you don't want duplicates from the first list:假设您不希望 list1 中出现重复的条目,则可以使用以下生成器来迭代所有组合:
但是,这不会以不同的顺序从 list1 中选择相同的选项。如果你想同时获得 [a1, a2, b1] 和 [a2, a1, b1] 那么你可以使用:
Assuming you don't want duplicate entries from list1, here's a generator that you can use to iterate over all combinations:
This, however, doesn't select the same options from list1 in different orderings. If you want to get both [a1, a2, b1] and [a2, a1, b1] then you can use:
您可以使用 itertools.product 来实现此目的。它返回所有可能的组合。
例如,
这将产生“双精度”为 [a1,a1,b2] 和 [a2,a3,b2],[a3,a2,b2]。您可以使用过滤器解决此问题。以下内容可防止任何双打*:
(*) 这假设选项具有某种自然顺序,所有原始值都是这种情况。
尚的答案也很好。我写了一些代码来比较它们:
结果是:
所以生成器方法更快。然而,速度并不是一切。就我个人而言,我发现我的代码“更干净”,但选择权在你!
(顺便说一句,它们给出了相同的计数,因此两者同样正确。)
You can use itertools.product for this. It returns all possible combinations.
For example
This will produce "doubles" as [a1,a1,b2] and [a2,a3,b2],[a3,a2,b2]. You can fix this with a filter. The following prevents any doubles*:
(*) This assumes that the options have some natural ordering which will be the case with all primitive values.
shang's answer is also very good. I wrote some code to compare them:
And the result is:
So the generator method is faster. However, speed is not everything. Personally I find my code 'cleaner', but the choice is yours!
(Btw, they give both identical counts, so both are equally correct.)
在我看来,您正在寻找
itertools.product()
It sounds to me like you're looking for
itertools.product()
一种方法是使用 itertools.product。
One way to do is to use itertools.product.