在Python中测试所有组合 [英] Testing all combinations in Python

查看:50
本文介绍了在Python中测试所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两组选项:

optionList1 = [a1,a2,a3,...,an]
optionList2 = [b1,b2,b3,...,bn]

选项列表中的元素不一定相等,我必须从第一个选项列表中选择两次。如何确保我尝试了第一个列表中的2个选项和第二个列表中的一个的每种组合。下面是一个示例选择集...

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]


推荐答案

假设您不希望list1中有重复的条目,这是一个可用于迭代的生成器在所有组合上:

Assuming you don't want duplicate entries from list1, here's a generator that you can use to iterate over all combinations:

def combinations(list1, list2):
    return ([opt1, opt2, opt3]
            for i,opt1 in enumerate(list1)
            for opt2 in list1[i+1:]
            for opt3 in list2)

但是,这不会以不同的顺序从list1中选择相同的选项。如果要同时获取[a1,a2,b1]和[a2,a1,b1],则可以使用:

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:

def combinations(list1, list2):
    return ([opt1, opt2, opt3]
            for opt1 in list1
            for opt2 in list1
            for opt3 in list2 if opt1 != opt2)

这篇关于在Python中测试所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆