我有所有可能组合的大清单
items = ["Apple","Banana","Orange","Peach"]
combs = []
for c in combinations(items, 2)):
combs.append([c[0],c[1]])
给出了:
[['Apple', 'Banana'], ['Apple', 'Orange'], ['Apple', 'Peach'], ['Banana', 'Orange'], ['Banana', 'Peach'], ['Orange', 'Peach']]
用户可以从该列表中输入两个项目,
我想在列表中获得所述组合的索引。
我可以这样做如果用户按正确的顺序输入,如“Apple Banana”,但不是如果它是相反的“香蕉苹果”。因为没有[“Banana”,“Apple”]
我知道我可以在输入中使用排列,因此它既可以提供[“Banana”,“Apple”]和正确的['Apple','Banana']。但是如何在不使用嵌套for循环的情况下检查是否存在另一个?即使是这么小的检查也会导致12次迭代。
这是嵌套循环:
for pr in permutations([input1, input2], 2):
for comb in combinations(items, 2):
if ..........:
dosomething
答案 0 :(得分:2)
您无需构建所有组合;您要找的是set operations:
items = set(["Apple","Banana","Orange","Peach"])
if {input1, input2} <= items:
# valid subset
演示:
>>> items = set(["Apple","Banana","Orange","Peach"])
>>> {'Apple', 'Banana'} <= items
True
>>> {'Banana', 'Apple'} <= items
True
>>> {'Banana', 'Watermelon'} <= items
False
如果您想要组合的索引,那么您也可以使用组合创建集:
inputs = {input1, input2}
found = None
for i, combo in enumerate(combinations(items, 2)):
if set(combo) == inputs:
found = i
break
或者,作为生成器表达式:
inputs = {input1, input2}
found = next((i for i, c in enumerate(combinations(items, 2))
if set(c) == inputs), None)
演示:
>>> items = ["Apple","Banana","Orange","Peach"]
>>> inputs = {'Banana', 'Apple'}
>>> next((i for i, c in enumerate(combinations(items, 2)) if set(c) == inputs), None)
0