【问题标题】:How do you expand this list comprehension into for loops, to understand this recursive function?您如何将此列表理解扩展为 for 循环,以理解此递归函数?
【发布时间】:2016-05-03 13:38:43
【问题描述】:

我一直在尝试理解 senderle 的对这个问题的回答:- Cross product of sets using recursion

我发现处理 for 循环然后将它们转换为列表推导更简单。我正在努力解决这个问题,因为它有两个列表推导,所以我认为我们需要嵌套循环。 s函数返回两个列表的笛卡尔积。

def product(*seqs):
    if not seqs:
        return [[]]
    else:
        return [[x] + p for x in seqs[0] for p in product(*seqs[1:])]
# working example:        
x = [1, 2], [3, 4]
print(product(*x))
# gives: [[1, 3], [1, 4], [2, 3], [2, 4]]

如何重写product() 函数来扩展列表理解?

【问题讨论】:

    标签: python list python-3.x recursion list-comprehension


    【解决方案1】:

    您可以按照相同的顺序编写循环。诀窍是将开头的[x] + p 表达式移到末尾。那是改变顺序的部分。您可以将列表推导转换为生成器:

    for x in seqs[0]:
        for p in product(*seqs[1:]):
            yield [x] + p
    

    这将改变product() 的返回类型。如果你希望它返回列表而不是生成器,它看起来会很相似,只是需要额外的簿记。

    l = []
    
    for x in seqs[0]:
        for p in product(*seqs[1:]):
            l.append([x] + p)
    
    return l
    

    【讨论】:

    • 如果我能在返回列表而不是生成器方面提供帮助,我会给你一个额外的 +1。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-11-23
    • 2022-10-07
    • 2019-03-21
    • 2022-01-12
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    相关资源
    最近更新 更多