在 Julia 中,將字串視為迭代器(傳遞字符)的這些示例可以作業:
number = "1234"
notnumber = "123z"
isgood = all(isdigit, number) # true
isobad = all(isdigit, notnumber) # false
isgood = mapreduce(isdigit, &, number) # also true
isbad = mapreduce(isdigit, &, notnumber) # also false
myhex = mapreduce(codepoint, &, number) # 0x00000030
avector = map(codecode, collect(number))
但這不起作用,盡管 isdigit() 和 codepoint() 具有非常相似的簽名:
avector = map(codepoint, number) # causes error
為什么有時需要在字串上使用 collect() ?如果答案是因為 all() 和 mapreduce() 取 iter 而 map() 取 collection,請說明區別?
使用 collect() 和 map() 是否錯誤,因為它會導致更長的執行時間或更多的記憶體使用?
uj5u.com熱心網友回復:
其原因是,map和filter有一個特殊的實作AbstractString。他們迭代一個字串并回傳一個字串。因此,map要求您傳遞的函式回傳AbstractChar. 下面是一個例子:
julia> x = "a12b3"
"a12b3"
julia> map(uppercase, x)
"A12B3"
和一個類似的例子filter:
julia> filter(isdigit, x)
"123"
現在,如果您不想得到一個字串作為結果map而是一個向量,那么使用collect(正如您所注意到的那樣很昂貴),或使用理解:
julia> [codepoint(c) for c in x]
5-element Vector{UInt32}:
0x00000061
0x00000031
0x00000032
0x00000062
0x00000033
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/382323.html
上一篇:如何僅檢查Flutter中的字串是否有換行符或空格?(顫振,飛鏢)
下一篇:在多邊形中找到最大的內接矩形
