【发布时间】:2018-01-08 14:24:22
【问题描述】:
如果你能想到一个好的,请更新标题!
我有如下结构的数据:
chr pos A_block A_val
2 05 7 A,T,C
2 11 7 T,C,G
2 15 7 AT,C,G
2 21 7 C,A,GT
2 31 7 T,C,CA
2 42 9 T,C,G
2 55 9 C,G,GC
2 61 9 A,GC,T
2 05 12 AC,TG,G
2 11 12 A,TC,TG
预期输出:为了学习,我只想重写输出文件,和输入文件一样,但是使用我下面建议的过程。
我想: step 01: 一次只读取两个连续块的值(前 7 和 9)-> step 02: 将该数据存储在字典中,block numbers 为主唯一键 -> step 03: 将该字典返回给预定义函数进行解析。 -> 现在,读取块 (9 & 12) -> 重复相同的过程直到结束。
我在想这样的事情:
import req_packages
from collections import defaultdict
''' make a function that takes data from two blocks at a time '''
def parse_two_blocks(someData):
for key, vals in someData:
do ... something
write the obtained output
clear memory # to prevent memory buildup
''' Now, read the input file'''
with open('HaploBlock_toy.txt') as HaploBlocks:
header = HaploBlocks.readline()
# only reads the first line as header
''' create a empty dict or default dict. Which ever is better?'''
Hap_Dict = {}
Hap_Dict = defaultdict(list)
''' for rest of the lines '''
for lines in HaploBlocks:
values = lines.strip('\n').split('\t')
''' append the data to the dict for unique keys on the for loop, until the number of unique keys is 2 '''
Block = values[2]
Hap_Dict[Block].append(values[3])
do something to count the number of keys - how?
if keys_count > 2:
return parse_two_blocks(Hap_Dict)
elif keys_count < 2 or no new keys: # This one is odd and won't work I know.
end the program
因此,当代码执行时,它将从块 7 和 9 中读取数据,直到字典被填满并返回到预定义的函数。解析完成后,它现在可以只保留前一个解析的后一个块中的数据。这样它就只需要读取剩余的块。
预期输出: 我现在的主要问题是能够一次读取两个块。我不想在 `parse_two_blocks(someData)' 中添加关于如何解析信息的内在细节 - 这个只是另一个问题。但是,让我们尝试重写与输入相同的输出。
【问题讨论】:
-
你能举例说明你想要得到的结果吗?
-
@ComradeAndrew:我试图以这种方式解析数据,因为我必须一次读取两个块 -> 然后,进行适当的计算并写入值?为了我的学习和暂时将问题最小化,我只想编写与输入相同的输出文件。我可以自己操作。主要问题是一次读取两个块。
-
每个块是否包含 4 个条目的倍数?我建议您尝试创建所有行的列表,并使用双索引为它们行走,其中第一个索引在第一个块中,第二个在第二个块中移位 4。
-
不,它没有。它会有所不同。那只是一个巧合。对不起。我刚刚更新了数据
-
编写一个返回块列表的函数。然后编写另一个成对迭代该列表的函数。然后编写一个函数,使用块号作为键从列表中创建数据库。一些“功能”可能是单行列表推导。
标签: python list dictionary for-loop defaultdict