解释此reduce()如何生成所有子列表

时间:2017-09-03 01:39:05

标签: python python-3.x

我想知道这个表达是如何运作的。

f = lambda l: reduce(lambda z, x: z + [y + [x] for y in z], l, [[]])

此函数如何创建传递给它的数组中所有数字的子集。

输出:

f([10,9,1])

[[], [10], [9], [10, 9], [1], [10, 1], [9, 1], [10, 9, 1]]

2 个答案:

答案 0 :(得分:1)

如果你将lambda转换为函数,使用一些更好的变量名,并打印一些东西,你应该能够遵循逻辑:

def f(xs):
    results = [[]]
    return reduce(g, xs, results)

def g(results, x):
    results_with_x = [r + [x] for r in results]
    combined = results + results_with_x
    print('-----')
    print('r ', results)
    print('x ', x)
    print('rx', results_with_x)
    print('c ', combined)
    return combined

def main():
    xs = [10, 9, 1]
    results = f(xs)
    print('-----')
    print('  ', results)

main()

输出:

-----
r  [[]]
x  10
rx [[10]]
c  [[], [10]]
-----
r  [[], [10]]
x  9
rx [[9], [10, 9]]
c  [[], [10], [9], [10, 9]]
-----
r  [[], [10], [9], [10, 9]]
x  1
rx [[1], [10, 1], [9, 1], [10, 9, 1]]
c  [[], [10], [9], [10, 9], [1], [10, 1], [9, 1], [10, 9, 1]]
-----
   [[], [10], [9], [10, 9], [1], [10, 1], [9, 1], [10, 9, 1]]

答案 1 :(得分:0)

我们将lambda函数调用存储在f变量中,其中arg = [10,9,1] 关于发生的事情的简短描述:

reduce(lambda z, x: z + [y + [x]] for y in z, [10,9,1], [[]])
# inside reduce in short description:
it = [10,9,1]
accum_value = [[]]
for x in it:
    # accum_value = lambda z,x: z + [y + [x]] for y in z
    # where z = "accum_value" and x = element of "it" iterable. 
    # There this lambda calling each time of cycle with new params.

    # first in: 
    # accum_value = [[]] + [[]+[10]] = [[], [10]]

    # second in: 
    # accum_value = [[], [10]] + [[]+[9]]+[[10]+[9]] = [[], [10], [9], [9,10]]

    # third in: 
    # accum_value = [[], [10], [9], [9,10]] + [[]+[1]] + [[10]+[1]] + [[9]+[1]] + 
    # [[9,10]+[1]] = [[], [10], [9], [10, 9], [1], [10, 1], [9, 1], [10, 9, 1]]

return accum_value

所以,返回[[],[10],[9],[10,9],[1],[10,1],[9,1],[10,9,1]] < / p>