replace - 如何替换Julia中字符串中的多个字符

标签 replace julia

我尝试过以下功能。 示例:

dna = "ACGTGGTCTTAA"
function to_rna(dna)
    for (nucleotides1, nucleotides2) in zip("GCTA", "CGAU")
        dna = replace(dna, nucleotides1 => nucleotides2)
    end
    return dna
end

输出:“UGGUGGUGUUUU”,这不是预期的。

预期输出:“UGCACCAGAAUU”

有人可以指出哪里出了问题吗?

最佳答案

您正在按顺序执行每个字母的替换:

julia> function to_rna(dna)
           for (nucleotides1, nucleotides2) in zip("GCTA", "CGAU")
               dna = replace(dna, nucleotides1 => nucleotides2)
               @show nucleotides1 => nucleotides2
               @show dna
           end
           return dna
       end
to_rna (generic function with 1 method)

julia> to_rna(dna)
nucleotides1 => nucleotides2 = 'G' => 'C'
dna = "ACCTCCTCTTAA"
nucleotides1 => nucleotides2 = 'C' => 'G'
dna = "AGGTGGTGTTAA"
nucleotides1 => nucleotides2 = 'T' => 'A'
dna = "AGGAGGAGAAAA"
nucleotides1 => nucleotides2 = 'A' => 'U'
dna = "UGGUGGUGUUUU"
"UGGUGGUGUUUU"

julia> dna
"ACGTGGTCTTAA"

也就是说,在第一步等之后,您无法区分 RNA C 和 DNA C

你希望它并行工作——就像这样:

julia> to_rna2(dna) = map(dna) do nucleotide
           NUCLEOTIDE_MAPPING[nucleotide]
       end
to_rna2 (generic function with 1 method)

julia> NUCLEOTIDE_MAPPING = Dict(n1 => n2 for (n1, n2) in zip("GCTA", "CGAU"))
Dict{Char,Char} with 4 entries:
  'A' => 'U'
  'G' => 'C'
  'T' => 'A'
  'C' => 'G'

julia> to_rna2(dna)
"UGCACCAGAAUU"

这也消除了对字符串进行四次迭代的不必要的工作。

replace 本身已经能够做到这一点——如果你给它一个数组并传递给它多个替换参数:

julia> replace(collect(dna), NUCLEOTIDE_MAPPING...)
12-element Array{Char,1}:
 'U'
 'G'
 'C'
 'A'
 'C'
 'C'
 'A'
 'G'
 'A'
 'A'
 'U'
 'U'

要返回字符串而不是数组,您只需再次加入即可:

julia> replace(collect(dna), NUCLEOTIDE_MAPPING...) |> join
"UGCACCAGAAUU"

关于replace - 如何替换Julia中字符串中的多个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63357132/

相关文章:

mysql - 清理充满 html 标签的旧数据库

C#:删除两个定界符之间的所有字符

julia - 如何在 Julia 中处理分类数据?

julia - 离线使用 Julia 包管理器

julia - 默认项目中的包

julia - 矩阵列上的内存高效 sortperm

r - 合并两个 data.frames 并用 df2 的值替换 df1 某些列的值

asp.net - asp.net如何替换字符串中的特殊字符

julia - 在 for 循环中使用增量

python - 拆分列表中的字符串以查找和替换 python 中的元素