Jos*_*ath 3 arrays list-comprehension break julia
我在Julia中有以下代码行:
X=[(i,i^2) for i in 1:100 if i^2%5==0]
Run Code Online (Sandbox Code Playgroud)
基本上,它返回一个元组列表(i,i^2)
,从i=1 to 100
如果剩余i^2
和5
为零.我想要做的是,在数组理解中,如果i^2
变得大于,则跳出for循环1000
.但是,如果我实施
X=[(i,i^2) for i in 1:100 if i^2%5==0 else break end]
Run Code Online (Sandbox Code Playgroud)
我收到错误:syntax: expected "]"
.
有没有办法轻松打破数组内的for循环?我试过在网上看,但没有出现.
这是一个"假的"for-loop,所以你不能break
.看看下面的降低代码:
julia> foo() = [(i,i^2) for i in 1:100 if i^2%5==0]
foo (generic function with 1 method)
julia> @code_lowered foo()
LambdaInfo template for foo() at REPL[0]:1
:(begin
nothing
#1 = $(Expr(:new, :(Main.##1#3)))
SSAValue(0) = #1
#2 = $(Expr(:new, :(Main.##2#4)))
SSAValue(1) = #2
SSAValue(2) = (Main.colon)(1,100)
SSAValue(3) = (Base.Filter)(SSAValue(1),SSAValue(2))
SSAValue(4) = (Base.Generator)(SSAValue(0),SSAValue(3))
return (Base.collect)(SSAValue(4))
end)
Run Code Online (Sandbox Code Playgroud)
输出显示array comprehension
通过Base.Generator
它实现迭代器作为输入.它现在只支持[if cond(x)::Bool]
"后卫",所以这里没有办法使用break
.
对于您的具体情况,解决方法是使用isqrt
:
julia> X=[(i,i^2) for i in 1:isqrt(1000) if i^2%5==0]
6-element Array{Tuple{Int64,Int64},1}:
(5,25)
(10,100)
(15,225)
(20,400)
(25,625)
(30,900)
Run Code Online (Sandbox Code Playgroud)
我不这么认为.你可以永远
tmp(i) = (j = i^2; j > 1000 ? false : j%5==0)
X=[(i,i^2) for i in 1:100 if tmp(i)]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
459 次 |
最近记录: |