gpt4 book ai didi

python - Nim相当于Python的列表理解

转载 作者:太空狗 更新时间:2023-10-29 17:15:17 26 4
gpt4 key购买 nike

由于 Nim 与 Python 共享很多功能,如果它实现了 Python's list comprehension,我不会感到惊讶。也是:

string = "Hello 12345 World"
numbers = [x for x in string if x.isdigit()]
# ['1', '2', '3', '4', '5']

这在 Nim 中真的可行吗?如果没有,可以用模板/宏实现吗?

最佳答案

更新:自版本 0.19.9 ( Source ) 以来,列表理解已被弃用。一个好的替代方法是使用 the new sugar.collect macro .


列表理解是在 Nim 中实现的 sugar package (即,您必须 import sugar)。它被实现为一个名为 lc 的宏,并允许像这样编写列表推导式:

lc[x | (x <- 1..10, x mod 2 == 0), int]

lc[(x,y,z) | (x <- 1..n, y <- x..n, z <- y..n, x*x + y*y == z*z), tuple[a,b,c: int]]

请注意,宏需要指定元素的类型。

关于python - Nim相当于Python的列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29895918/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com