小编Con*_*ntC的帖子

如何在列表理解中使用 if-else

我想比较两个列表理解的执行时间,一个使用 if-else 关键字,另一个使用三元运算符。

arr = [5, 8, 12, 17, 24, 42];

function squares_and_cubes(array)
    return [ x%2 ==0 ?  x^2 : x^3 for x in array]
end

function squares_and_cubes_if_else(array)
    [ x^2 if (x%2==0) else x^3 end for x in array]
end
@time squares_and_cubes(arr)
@time squares_and_cubes_if_else(arr) 
Run Code Online (Sandbox Code Playgroud)

ERROR: syntax: invalid comprehension syntax 但是,我在尝试执行时收到以下错误消息[ x^2 if (x%2==0) else x^3 end for x in arr]。作为 Julia 新手,我无法弄清楚这种语法有什么问题 - 我正在使用 v 1.7 。

if-statement list-comprehension julia

3
推荐指数
1
解决办法
452
查看次数

标签 统计

if-statement ×1

julia ×1

list-comprehension ×1