首页 > 解决方案 > 使用枚举在python中打印上一行

问题描述

我有一个以下格式的文件。

OperonID    GI      Synonym    Start    End  Strand Length  COG_number  Product
1132034 397671780   RVBD_0002   2052    3260    +   402 -   DNA polymerase III subunit beta
1132034 397671781   RVBD_0003   3280    4437    +   385 -   DNA replication and repair protein RecF
1132034 397671782   RVBD_0004   4434    4997    +   187 -   hypothetical protein
1132035 397671783   RVBD_0005   5123    7267    +   714 -   DNA gyrase subunit B
1132035 397671784   RVBD_0006   7302    9818    +   838 -   DNA gyrase subunit A
1132036 397671786   RVBD_0007Ac 11421   11528   -   35  -   hypothetical protein
1132036 397671787   RVBD_0007Bc 11555   11692   -   45  -   hypothetical protein
1132037 397671792   RVBD_0012   14089   14877   +   262 -   hypothetical protein

我知道到目前为止我可能可以使用 enumerate 并拥有以下脚本。

lines = open('operonmap.opr', 'r').read().splitlines()
operon_id = 1132034
start = ''
end = ''
strand = ''

for i,line in enumerate(lines):
      if str(operon_id) in line:
            start += line[28:33]
      else:
            end += line[i-1]
            operonline += start
            operonline += end
            operonline += '\n'

然后,如果这种脚本有效,我将编辑字符串“operonline”以仅包含起始端和链信息。不幸的是它不起作用,但我希望你能看到我的逻辑。

我希望有人能够提供帮助!

标签: python

解决方案


如果你使用熊猫,这很容易,如果你想走那条路..

我能够将您的数据读入pandas DataFrame然后删除其他列:

   Start    End Strand OperonID
0   2052   3260      +  1132034
1   3280   4437      +  1132034
2   4434   4997      +  1132034
3   5123   7267      +  1132035
4   7302   9818      +  1132035
5  11421  11528      -  1132036
6  11555  11692      -  1132036
7  14089  14877      +  1132037

然后我将and和value分组OperonID并存储为列表,并创建了一个新列,其中包含第一个和最后一个per以及唯一值..您可以以任何您认为合适的方式重新组织它StartEndStrandStartEndOperonIDStrand

df2 = df.groupby('OperonID')[['Start', 'End', 'Strand']].agg(list)
df2['result'] = df2.apply(lambda x: (x['Start'][0], x['End'][-1], set(x['Strand'])), axis=1)

df2['result']:

OperonID
1132034      (2052, 4997, {+})
1132035      (5123, 9818, {+})
1132036    (11421, 11692, {-})
1132037    (14089, 14877, {+})

推荐阅读