如何在Julia中替换字符串中的几个字符

问题描述

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

import Head from 'next/head'
import styles from '../styles/Home.module.css'
import Router from 'next/router'
import React,{ useEffect } from "react";
import { Redirect } from 'react-router';


export default function Home(props) {
  useEffect(() => {
    const { pathname } = Router
    if (pathname == '/') {
      Router.push('/login');
    }
  },[props]);

  return ''
}

输出:dna = "ACGTGGTCTTAA" function to_rna(dna) for (nucleotides1,nucleotides2) in zip("GCTA","CGAU") dna = replace(dna,nucleotides1 => nucleotides2) end return dna end ,这是不期望的。

预期输出:"UGGUGGUGUUUU"

有人能指出出什么问题了吗

解决方法

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

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'

要取回字符串而不是数组,只需再次join

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...