[英]Nim equivalent of Python's list comprehension
由於 Nim 與 Python 共享很多特性,如果它也實現了Python 的列表推導,我不會感到驚訝:
string = "Hello 12345 World"
numbers = [x for x in string if x.isdigit()]
# ['1', '2', '3', '4', '5']
這在 Nim 中真的可能嗎? 如果沒有,可以用模板/宏來實現嗎?
更新:列表理解自 0.19.9 版( 來源)以來已被棄用。 一個不錯的選擇是使用新的 sugar.collect 宏。
列表理解在 Nim 中的sugar
包中實現(即,您必須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]]
請注意,宏需要指定元素的類型。
根據rosettacode , Nim 沒有列表推導,但它們可以通過元編程創建。
[編輯]
正如 bluenote10 所指出的,列表推導現在是未來模塊的一部分:
import future
var str = "Hello 12345 World"
echo lc[x | (x <- str, ord(x) - ord('0') in 0..9), char]
上面的代碼片段產生@[1, 2, 3, 4, 5]
原來的
import sugar
let items = collect(newSeq):
for x in @[1, 2, 3]: x * 2
echo items
輸出@[2, 4, 6]
更新以回答問題
import sugar
import sequtils
import strutils
let numbers = collect: # collect from suger
for x in "Hello 12345 World".toSeq: # toSeq from sequtils
if x.isDigit: # isDigit from strutils
x
echo numbers
輸出@['1', '2', '3', '4', '5']
您的代碼的 Nim 翻譯:
import sugar, strutils
var str = "Hello 12345 World"
echo collect(for s in str:
if s.isDigit(): s)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.