Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python字符串/数组中的多个指定位置插入值_Python_Bioinformatics - Fatal编程技术网

在python字符串/数组中的多个指定位置插入值

在python字符串/数组中的多个指定位置插入值,python,bioinformatics,Python,Bioinformatics,我想在python字符串/数组中插入多个指定位置的值 例如,对于我的输入字符串:SARLSAMLVPVTPEVKPK 在指定位置:1,5,12 所需输出:S*ARLS*AMLVPVT*PEVKPK 我试过: seq="SARLSAMLVPVTPEVKPK" #string pos=[1,5,12] #positions arr=list(seq) #convert string to array arr.insert(pos,"*") # NOT WORK! arr.insert(pos[0],

我想在python字符串/数组中插入多个指定位置的值

例如,对于我的输入字符串:
SARLSAMLVPVTPEVKPK

在指定位置:1,5,12

所需输出:
S*ARLS*AMLVPVT*PEVKPK

我试过:

seq="SARLSAMLVPVTPEVKPK" #string
pos=[1,5,12] #positions
arr=list(seq) #convert string to array
arr.insert(pos,"*") # NOT WORK!
arr.insert(pos[0],"*")
print(''.join(arr))
似乎我一次只能插入一个位置,因此下一次插入的指定位置的索引必须更改。 是否有一种优雅的方法可以做到这一点,或者我必须循环插入位置,为每个额外的插入位置添加+1? 我希望这是有意义的

非常感谢,,
卷曲。

像这样的东西可以:

seq="SARLSAMLVPVTPEVKPK" #string
pos=[1,5,12] #positions
arr=list(seq) #convert string to array
_ = map(lambda k: arr.insert(k, "*"), pos[::-1])
print(''.join(arr))


这样做可以:

seq="SARLSAMLVPVTPEVKPK" #string
pos=[1,5,12] #positions
arr=list(seq) #convert string to array
_ = map(lambda k: arr.insert(k, "*"), pos[::-1])
print(''.join(arr))

简单方法:

temp =  ""
temp += seq[:pos[0]]
temp += "*"
for i in range(1,len(pos)):
    temp += seq[pos[i-1]:pos[i]]
    temp += "*"
temp += seq[pos[-1]:]
print (temp)    # 'S*ARLS*AMLVPVT*PEVKPK'
简单方法:

temp =  ""
temp += seq[:pos[0]]
temp += "*"
for i in range(1,len(pos)):
    temp += seq[pos[i-1]:pos[i]]
    temp += "*"
temp += seq[pos[-1]:]
print (temp)    # 'S*ARLS*AMLVPVT*PEVKPK'

只需按相反顺序插入即可:

seq="SARLSAMLVPVTPEVKPK" #string
pos=[1,5,12] #positions
arr = list(seq)
for idx in sorted(pos, reverse=True):
    arr.insert(idx,"*")
print ''.join(arr)

只需按相反顺序插入即可:

seq="SARLSAMLVPVTPEVKPK" #string
pos=[1,5,12] #positions
arr = list(seq)
for idx in sorted(pos, reverse=True):
    arr.insert(idx,"*")
print ''.join(arr)

我唯一不喜欢的是每次插入时都会生成一个新字符串。我不知道这个的时间代价是什么。Temp是一个字符串,字符串是不可变的,您创建一个新字符串并将其保存在Temp变量中。无论如何,这个解决方案比我的要花更少的时间^ ^ ^我唯一不喜欢的是每次插入时都要生成一个新字符串。我不知道这个的时间代价是什么。Temp是一个字符串,字符串是不可变的,您创建一个新字符串并将其保存在Temp变量中。不管怎么说,这个解决方案比我的时间要少^_^