将Python代码转换为C代码
我试图将itertools.product()python的函数转换为C代码:将Python代码转换为C代码,python,itertools,Python,Itertools,我试图将itertools.product()python的函数转换为C代码: def product(*args, repeat=1): pools = [tuple(pool) for pool in args] * repeat result = [[]] for pool in pools: result = [x+[y] for x in result for y in pool] for prod in result:
def product(*args, repeat=1):
pools = [tuple(pool) for pool in args] * repeat
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
到C代码,但我不理解此特定说明:
result = [x+[y] for x in result for y in pool]
谁能给我解释一下吗?
谢谢这是个好主意。它相当于以下内容-
result = []
for x in result:
for y in pool:
result.append(x+[y])
正如Ashish指出的,这是一个列表理解。在短列表中,理解基本上只是一个循环的一行程序,其中包含一个可选的条件语句(或多个条件语句),返回一个数组
[ expression for item in list if conditional ]
相当于
for item in list:
if conditional:
expression
列表理解将返回该循环中所有表达式结果的数组
result = [ x+1 for x in [0,1,2] ]
将依次执行0+1,将值保存在数组中,然后对1+1和2+1执行相同的操作。最后的结果是[1,2,3]