如何展开列表理解

时间:2017-10-09 03:56:39

标签: python algorithm list-comprehension powerset loop-unrolling

我正在尝试理解以下代码,因为我是Python的新手。我知道代码计算powerset但行subsetlist = [ subset + [item] for subset in result]有点难以理解。我怎样才能将这个复合线分解为简单的循环以便理解。

def powerset(x):
    result = [[]]
    for item in x:
        subsetlist = [ subset + [item] for subset in result]
        result.extend(subsetlist)
    return result

这是我试图让它更简单但它似乎不起作用。我的IDLE卡住了,不打印任何东西。

def powerset(x):
    result = [[]]
    for item in x:
        for subset in result:
            result.append(item)
    print(result)

1 个答案:

答案 0 :(得分:2)

提示:

你非常接近。只需在第二个循环中移动空列表。

工作代码:

def powerset(x):
    result = [[]]
    for item in x:
        subsetlist = []
        for subset in result:
            subsetlist.append(subset + [item])
        result.extend(subsetlist)
    return result

来自IDLE的输出:

>>> powerset('abc')
[[], ['a'], ['b'], ['a', 'b'], ['c'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']]