将 Python 代码转换为 C 代码

马文·考维纳

我试图将 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:
        yield tuple(prod)

到 C 代码,但我不明白这个特殊的指令:

result = [x+[y] for x in result for y in pool]

谁能为我解释一下?谢谢

埃德温·克拉夫琴科

正如 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]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章