2017-04-05 88 views
3

我想找到x的元素,其中包含"X"并用“”替换"X"。使用用Julia替换向量字符串

v = split("a b c d e f g h i j k l m n o p X") 
x = rand(v,100) .* rand(v,100) .* rand(v,100) 

A中的for循环我可以:

for i=1:length(x) 
    x[i] = replace(x[i], "X", "") 
    end 

这是串矢量操作是如何在朱莉娅做了什么?或者是否有.replaceapplysapply(x, replace, "X", "")用于R)我应该使用的函数集?

+1

这是一个很好的方法来做到这一点。你可以使用'map!'来更简洁一些:'map!(s-> replace(s,“X”,“”),x,x)' – StefanKarpinski

+1

请记住,范围也适用于角色:''a':'z'是一个有效范围,'string。('a':'z')'产生一个字符串向量。在你的特定情况下,由于'X',你需要做一个额外的步骤:'v = string。(['a':'p';'X'])''。无论如何,我认为比输入所有字母更方便。 – DNF

回答

2

你可以不喜欢它

[replace(i,"X","") for i in x] 

但作为斯特凡在评论中指出,它会创建一个新的载体。 正确的方法应该

x .= replace.(x, "X", "") 

(由马特解释)正好有替代功能的快速回顾一下,这里是朱莉娅官方文档说什么。

help?> replace 
search: replace redisplay 

    replace(string, pat, r[, n]) 

    Search for the given pattern pat, and replace each occurrence with r. If n is provided, replace at most n occurrences. As 
    with search, the second argument may be a single character, a vector or a set of characters, a string, or a regular 
    expression. If r is a function, each occurrence is replaced with r(s) where s is the matched substring. If pat is a 
    regular expression and r is a SubstitutionString, then capture group references in r are replaced with the corresponding 
    matched text. 

julia> 
+0

这可以产生一个带有替换的新向量,但它不会修改字符串'x'的向量。 – StefanKarpinski

+0

哦,是的,@StefanKarpinski。谢谢 –

3

使用循环或理解是一个很好的解决方案,通常是一个非常高效的解决方案。循环在Julia中很快,所以你不需要担心向量化代码只是为了让它快速。这就是说,在即将到来的0.6版本中,您可以在朱莉娅using dot-broadcasting写快量化代码,因为串现在在广播当作标量元素:

x .= replace.(x, "X", "") 

julia> replace.(x, "X", "") 
100-element Array{String,1}: 
"lod" 
"kk" 
"eco" 
"jac" 
⋮ 
"ojn" 
"hmc" 
"pb" 

你可以做到就地