簡體   English   中英

在循環中連接不同長度的字符串

[英]Joining strings of different lengths in a loop

我正在嘗試從這種格式轉換文件:

# 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收到消息IndexError: string index out of range

這是腳本的一部分:計算出附加到InputMasterList中的字符串長度(即seq1aseq2aseq1bseq2b ),將帶有額外零的SampleName s添加到OutputMasterList 然后它應該附加到OutputMasterList通過選擇開始元素[0]從每個連續元件的串InputMasterList[LineEven]串( seq1aseq2a )和InputMasterList[LineOdd]串( seq1bseq2b )和它們放在一起分組到OutputMasterList 所以結果將是( sseeqq 1 1 absseeqq 2 2 ab )。

如何讓這個腳本在不同的字符串長度上工作?

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

我是一個非常初學者,所以我知道這段代碼非常繁瑣,但任何幫助都將不勝感激。 如果您需要澄清我試圖用這個腳本做什么,請不要猶豫。

更新:感謝您的及時回復。 由於您的反饋,我意識到我必須改變我的問題的性質。 在我的數據集中,我缺少了我的腳本不喜歡的序列,我需要使用占位符來解釋這個缺失的數據,占位符與其對應的長度相同。

舊格式:

# SampleNamea   seq1a   seq2a

# SampleNameb   '.'      seq2b

新格式:

# SampleNamea   seq1a   seq2a

# SampleNameb   NNNNN   seq2b

然后我相信我的腳本會起作用!

TL; DR - 根據您的反饋,我的基礎是我的下一步應該是什么。

根據您的新更新,InputMasterList [LineOdd]字符串可能看起來像(.seq2b)。

然后在繼續追加之前,檢查InputMasterList

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

您可以為LineOdd和LineEven執行此操作

注意 :這取決於您的新輸入

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM