简体   繁体   English

朱莉娅的条件理解

[英]Conditional comprehension in Julia

In Python, there is the option to provide a condition for whether or not to include a specific item in a comprehension. 在Python中,可以选择为是否在理解中包含特定项目提供条件。

[x**2 for x in range(10) if x > 5]
# [36, 49, 64, 81]

It is possible to conditionally use function, but I have not yet found a way to entirely exclude values, other than filter! 有条件地使用函数是可能的,但我还没有找到一种方法来完全排除值,除了filter! ing them outside of the comprehension. 使他们超出理解范围。

l = collect(0:9)
filter!(x -> x > 5, l)
l = [x^2 for x in l]  # alternatively, map!(x -> x^2, l)
# [36, 49, 64, 81]

Is this possible in Julia? 朱莉娅有可能吗?

It is possible in the latest Julia. 有可能在最新的朱莉娅。

julia> [x^2 for x in 0:9 if x > 5]
4-element Array{Int64,1}:
 36
 49
 64
 81

Otherwise, yes, if you're using pre 0.5 you're stuck with: 否则,是的,如果你使用的是前0.5,你会被困在:

[x^2 for x in filter((x) -> x > 5, 0:9)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM