Python从列中聚类数据

2024-09-27 18:18:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个文件:

EgrG_000961100.1    IPR001611
EgrG_000961100.1    IPR032675
EgrG_000961100.1    IPR000742
EgrG_000961100.1    IPR001791
EgrG_000961100.1    IPR001611
EgrG_000989200.1    IPR000668
EgrG_000989200.1    IPR013201
EgrG_000989200.1    IPR025660
EgrG_000989200.1    IPR000668
EgrG_000989200.1    IPR025661
EgrG_000989200.1    IPR000169
EgrG_000704400.1    IPR013780
EgrG_000704400.1    IPR015341
EgrG_000704400.1    IPR011682
EgrG_000704400.1    IPR015341
EgrG_000704400.1    IPR011013

我想为每个ID写一行(ID=EgrG_876;*),下一列包含该ID的所有IPR,如下所示:

EgrG_000961100.1    IPR001611|IPR032675|IPR000742|IPR001791|IPR001611
EgrG_000989200.1    IPR000668|IPR025660|IPR000668|IPR025661|IPR000169
EgrG_000704400.1    IPR013780|IPR015341|IPR011682|IPR015341|IPR011013

我不知道怎么用python写这个。 提前谢谢


Tags: 文件idegrgipr000668ipr013780ipr025660ipr000742ipr025661
1条回答
网友
1楼 · 发布于 2024-09-27 18:18:00
f =  open("file","r+")
lines = f.readlines() 
f.close()
dict = {} #create a dictionary where the key is your ID and the value a list with IPR
for line in lines:
     ID,IPR = line.split("/t") #I assume your txt file is TAB seperated
     if dict.has_key(ID):
          dict[ID] = dict[ID]+[IPR]
     else:
          dict[ID] = [IPR]

当你有字典的时候,就按你想要的方式把它写进一个文件。 我想这会管用的。可能有更好或更快的解决方案,但我希望它会有所帮助

相关问题 更多 >

    热门问题