在循环中连接不同长度的字符串

时间:2016-07-27 16:47:33

标签: python

我正在尝试从这种格式转换文件:

# SampleNamea   seq1a   seq2a
# SampleNameb   seq1b   seq2b
# SampleNamec   seq1c   seq2c
# SampelNamed   seq1d   seq2d

采用以下格式:

# SampleNamea   SampleNameb 0   0   0   0   s   s   e   e   q   q   1   1   a   b   s   s   e   e   q   q   2   2   a   b
# SampleNamec   SampleNamed 0   0   0   0   s   s   e   e   q   q   1   1   c   d   s   s   e   e   q   q   2   2   c   d

目前,如果seq1aseq1b等长度相同,我可以使用的脚本。但是在数据集中我的字符串长度各不相同。如果我尝试在我的数据集上运行脚本,则会收到消息IndexError: string index out of range

这是脚本的一部分:找出附加到seq1aseq2a的字符串长度(即seq1bseq2bInputMasterList),添加{{1}带有SampleName的额外零的s。然后,它应该通过从OutputMasterList字符串(OutputMasterList)和InputMasterList[LineEven]字符串({{}中选择以元素[0]开头的每个连续元素来追加seq1aseq2a字符串。 1}})并将它们组合成InputMasterList[LineOdd]。所以结果将是(seq1bseq2b)。

如何让这个脚本处理不同的字符串长度?

OutputMasterList

我是一名初学者,所以我知道这段代码非常繁琐,但任何帮助都会受到赞赏。如果您需要澄清我试图用这个脚本做什么,请不要犹豫。

更新: 感谢您的及时回复。由于您的反馈,我意识到我必须改变我的问题的性质。在我的数据集中,我缺少了我的脚本不喜欢的序列,我需要使用占位符来解释这个缺失的数据,占位符与其对应的长度相同。

旧格式:

s s e e q q 1 1 a b s s e e q q 2 2 a b

新格式:

LineEven = 0
LineOdd = 1
RecordNum = 1

while RecordNum < (NumofLinesInFile/2):
    for i in range(len(InputMasterList[LineEven])):
        if i == 0:
            OutputMasterList.append(SampleList[LineEven]+'\t'+ SampleList[LineEven]+'\t'+'0'+'\t'+'0'+'\t'+'0'+'\t'+'0'+'\t')
        OutputMasterList[RecordNum] = InputMasterList[LineEven][i]+'\t'+InputMasterList[LineOdd][i]+'\t'
    RecordNum = RecordNum + 1
    LineEven = LineEven + 2
    LineOdd = LineOdd + 2

然后我相信我的脚本会起作用!

TL; DR - 根据您的反馈,我的基础是我的下一步应该是什么。

1 个答案:

答案 0 :(得分:0)

根据您的新更新,

InputMasterList [LineOdd]字符串可能看起来像(.seq2b)。

然后在继续追加之前,检查InputMasterList

if '.' in InputMasterList[LineOdd]:
    InputMasterList[LineOdd] = InputMasterList[LineOdd].replace('.', 'NNNNN', 1)

您可以为LineOdd和LineEven

执行此操作

注意:这取决于您的新输入

相关问题