Python 在字符串列表中的空格中插入字符

Python 在字符串列表中的空格中插入字符,python,string,append,bioinformatics,Python,String,Append,Bioinformatics,我试图通过在每行的空格之间添加“->”和“:”来添加字符串列表。我当前的输出如下所示: 0 1 A 1 2 T 2 3 A 3 4 G 4 5 A 2 6 C 0 7 G 7 8 A 8 9 T 但我希望它看起来像: 0->1:A 1->2:T 2->3:A 3->4:G 4->5:A 2->6:C 0->7:G 7->8:A 8->9:T 你可以在下面找到我正在使用的代码 def trie_edges(patterns): my

我试图通过在每行的空格之间添加“->”和“:”来添加字符串列表。我当前的输出如下所示:

0 1 A
1 2 T
2 3 A
3 4 G
4 5 A
2 6 C
0 7 G
7 8 A
8 9 T
但我希望它看起来像:

0->1:A
1->2:T
2->3:A
3->4:G
4->5:A
2->6:C
0->7:G
7->8:A
8->9:T
你可以在下面找到我正在使用的代码

def trie_edges(patterns):
    myTrie = trieConstruction(patterns)
    sortMatrix = lambda item: ' '.join(map(str,item[0]))+' '+item[1]
    return map(sortMatrix, myTrie.edges.items())

def main():

    with open('C:/Users/Sami/PycharmProjects/Bioinformatics/rosalind_ba2d.txt') as input_data:
    patterns = [line.strip() for line in input_data.readlines()]
    createMatrix = trie_edges(patterns)
    print ('\n'.join(createMatrix))

您的
sortMatrix
lambda函数创建该格式

sortMatrix = lambda item: ' '.join(map(str,item[0]))+' '+item[1]
它在所有项目之间插入空格

我会这样做:

sortMatrix = lambda item: '->'.join(map(str,item[0]))+':'+item[1]
因此,前两个术语用
->
分隔,另一个用

使用
format
和drop
join
可能会更好,因为这对2个元素来说是多余的(这样可以节省
映射(str
东西:

sortMatrix = lambda item: "{}->{}:{}".format(item[0][0],item[0][1],item[1])

或者,内部
re.sub
替换每行中的第一个空格,并将其结果传递给外部
re.sub
,后者替换每行中的第二个空格

>>> from io import StringIO
>>> source = StringIO('''\
... 0 1 A
... 1 2 T
... 2 3 A
... 3 4 G
... 4 5 A
... 2 6 G''')
>>> import re
>>> for line in source.readlines():
...     re.sub(' ', ':', re.sub(' ','->',line.strip(),1))
... 
'0->1:A'
'1->2:T'
'2->3:A'
'3->4:G'
'4->5:A'
'2->6:G'

sortMatrix=lambda item:'->'有什么问题。加入(map(str,item[0])+':'+item[1]
@Jean-Françoisfare这很好用,谢谢!