簡體   English   中英

從enumerate()訪問每個索引結果-Python

[英]Access each index result from enumerate() - Python

我有數據,看起來像這樣:

Name Nm1    *    *
Ind1     AACTCAGCTCACG
Ind2     GTCATCGCTACGA 
Ind3     CTTCAAACTGACT

我需要從“名稱”行中用星號標記的每個位置抓取字母,並將其連同星號的索引一起打印

所以結果是

Ind1, 12, T
Ind2, 12, A
Ind3, 12, C
Ind1, 17, T
Ind2, 17, T
Ind3, 17, T

我試圖使用enumerate()檢索星號的位置,然后我的想法是,我可以使用這些索引來獲取字母。

import sys
import csv

input = open(sys.argv[1], 'r')
Output = open(sys.argv[1]+"_processed", 'w')

indlist = (["Individual_1,", "Individual_2,", "Individual_3,"])

with (input) as searchfile:
    for line in searchfile:
        if '*' in line:
            LocusID = line[2:13]
            LocusIDstr = LocusID.strip()
            hit = line
            for i, x in enumerate(hit):
                     if x=='*':
                      position = i
                      print position

    for item in indlist:
        Output.write("%s%s%s\n" % (item, LocusIDstr, position))

Output.close()

如果enumerate()輸出例如

12
17

如何分別訪問每個索引?

另外,當我打印位置時,我會得到想要的數字。 但是,當我寫入文件時,僅寫入最后一個位置。 為什么是這樣?

- - - - - - - - 編輯 - - - - - - - - -

根據下面的建議,我已經編輯了我的代碼,使對我來說更簡單了。

import sys
import csv

input = open(sys.argv[1], 'r')
Output = open(sys.argv[1]+"_FGT_Data", 'w')

indlist = (["Individual_1,", "Individual_2,", "Individual_3,"])

with (input) as searchfile:
    for line in searchfile:
        if '*' in line:
            LocusID = line[2:13]
            LocusIDstr = LocusID.strip()
            print LocusIDstr
            hit = line
            for i, x in enumerate(hit):
                    if x=='*':
                      position = i
                      #print position

input = open(sys.argv[1], 'r')

with (input) as searchfile:
    for line in searchfile:
        if line [0] == ">":
            print line[position], position

with (Output) as writefile:
    for item in indlist:
        writefile.write("%s%s%s\n" % (item, LocusIDstr, position))

Output.close()

但是,對於如何訪問每個索引,我仍然沒有解決方案。

編輯已更改,以處理您在評論中給我的文件。 如果您自己創建了此文件,請考慮下次使用列。

import sys

read_file = sys.argv[1]
write_file = "%s_processed.%s"%(sys.argv[1].split('.')[0],sys.argv[1].split('.')[1])
indexes = []
lines_to_write = []

with open(read_file,'r') as getindex:
    first_line = getindex.readline()
    for i, x in enumerate(first_line):
        if x == '*':
            indexes.append(i-11)

with open(read_file,'r') as getsnps:
    for line in getsnps:
        if line.startswith(">"):
            sequence = line.split("    ")[1]
            for z in indexes:
                string_to_append = "%s\t%s\t%s"%(line.split("    ")[0],z+1,sequence[z])
                lines_to_write.append(string_to_append)

with open(write_file,"w") as write_file:
    write_file.write("\n".join(lines_to_write))

暫無
暫無

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

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