我正在尝试理解以下代码,因为我是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)
答案 0 :(得分:2)
你非常接近。只需在第二个循环中移动空列表。
def powerset(x):
result = [[]]
for item in x:
subsetlist = []
for subset in result:
subsetlist.append(subset + [item])
result.extend(subsetlist)
return result
>>> powerset('abc')
[[], ['a'], ['b'], ['a', 'b'], ['c'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']]