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

Con*_*ntC 3 if-statement list-comprehension julia

我想比较两个列表理解的执行时间,一个使用 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 。

sun*_*ica 5

看来你正在尝试在这里使用类似 Python 的 if-else 语法。在朱莉娅中是:

julia> arr = [1, 2, 3, 4];

julia> [if (x%2==0) x^2 else x^3 end for x in arr]
4-element Vector{Int64}:
  1
  4
 27
 16
Run Code Online (Sandbox Code Playgroud)

执行时间应该没有差异,因为两者都被解析为几乎相同的抽象代码,并将生成完全相同的机器代码。(不过,为此目的,三元运算符更具可读性和惯用性。)

但如果您确实想满足自己的好奇心,请确保在计时之前运行这些函数一次,以避免测量编译时间。