我碰到下面的代码片段来(和可以跟踪其原产地https://docs.python.org/3/library/itertools.html#itertools.product):Python列表初始化:[]对[[]]
def cartesian_product(pools):
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
return result
a_list=[1, 2, 3]
b_list=[4, 5]
all_list=[a_list, b_list]
print (cartesian_product(all_list)) # [[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]
如果我们改变了以下行:
result = [[]]
对此:
result = []
然后代码不起作用。
现在考虑下面的代码,其中的变量my_list
初始化为my_list=[]
,而不是my_list=[[]]
,但我们仍然得到预期的结果:
my_list=[]
my_list.append([1,2])
my_list.append([3,4])
print (my_list) # [[1, 2], [3, 4]]
所以在功能cartesian_product
我上面提到的,有什么意义有result=[[]]
而不是result=[]
?
你确实注意到它遍历'result',对吧? –
如果'result'为空,'for result in'result'不会执行任何操作。 '[[]]'不是一个空列表,因此它做了一些不同的事情。 –