【问题标题】:Comparing Permutation and Combinations比较排列和组合
【发布时间】:2014-06-15 02:44:33
【问题描述】:

我有一个包含所有可能组合的大清单

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"]

我知道我可以在输入中使用排列,因此它可以同时给出 ["Banana", "Apple"] 和正确的 ['Apple', 'Banana']。但是如何在不使用嵌套 for 循环的情况下检查一个是否在另一个中?即使是这个小检查也会导致 12 次迭代。

这是嵌套循环:

for pr in permutations([input1, input2], 2):
    for comb in combinations(items, 2):
        if ..........:
            dosomething

【问题讨论】:

  • 使用set 存储组合怎么样?
  • Martijn 的答案是正确的。

标签: python compare combinations permutation


【解决方案1】:

您不需要构建所有组合;你要找的是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

如果您想要组合的索引,那么您也可以使用组合创建 sets

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

【讨论】:

  • 好吧,虽然我不知道这个,但这不是我要找的,我需要得到组合的索引。
猜你喜欢
  • 2018-05-15
  • 2010-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多