【问题标题】:Unique combinations from list with "distance limit"列表中带有“距离限制”的独特组合
【发布时间】:2018-09-09 09:26:39
【问题描述】:

鉴于列表a = ['a', 'b', 'c', 'd', 'e'],我将使用itertools.combinations 来获得所有独特的组合,如['ab', 'ac', ...],按照经典的SO answer

如何将唯一组合限制为不超过n 点的项目?

例子

如果我希望列出的项目不超过n=2 点,我会接受'ab' 和'ac' 作为组合但不接受'ae',因为'a' 和'e' 之间的距离大于@ 987654332@

编辑 - 代码

在普通的 python 代码解决方案之下,由于双 for 循环,我会避免这种解决方案,这对于大型列表来说并不理想

a = ['a', 'b', 'c', 'd', 'e']
n_items = len(a)
n_max_look_forward = 2

unique_combos = []
for i, item in enumerate(a):
    for j in range(i+1, min(i+n_max_look_forward+1, n_items)):
        unique_combos.append( item+a[j] )

print(unique_combos)

【问题讨论】:

    标签: python python-3.x combinations itertools


    【解决方案1】:

    就复杂性而言,您的解决方案已接近最佳解决方案。 您可以将其重构为仅在需要时生成值的生成器,这样您就不必同时将所有这些值保存在内存中:

    def combis(source, max_distance=2):
        for i, item in enumerate(source):
            for j in range(i+1, min(i+max_distance+1, len(source))):
                yield item+source[j]
    

    然后您可以遍历生成器:

    >>> for combi in combis(['a', 'b', 'c', 'd', 'e']):
    ...     print(combi)
    ...
    ab
    ac
    bc
    bd
    cd
    ce
    de
    

    如果您需要将它们全部作为列表保存在内存中,您仍然可以使用生成器对其进行初始化:

    >>> list(combis(['a', 'b', 'c', 'd', 'e']))
    ['ab', 'ac', 'bc', 'bd', 'cd', 'ce', 'de']
    

    【讨论】:

    • 我想我只能使用 1 个循环(将 i 和 j 保持在一个 while 循环中并增加一个或另一个)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    • 2011-03-31
    相关资源
    最近更新 更多