使用临时存储器进行智能计算

时间:2013-05-27 09:40:09

标签: python

我有一个代码,我需要遍历行并总结索引x,如果它们有匹配的索引[0]。什么是创造这个的最佳解决方案?我想我可能有defaultdict,如果index [0]中有匹配,它会添加值。有没有一种方法可以逐行读取它,并且索引[0]总是在临时内存中,如果它匹配下一个索引[0],它会做总结吗?

这是我到目前为止所做的:

with open("test.txt") as f:
    dic = defaultdict(list)
    for line in f:
        spl =line.split("\t")
        if("Fam" in line):
            dic[spl[0]].append(spl[1:])
            a = float(spl[5])
            b = float(spl[6])
            sum = a * b
            output = str(sum)
            this = line.strip() + "\t"+output
            if("TK" in line): #I would like to start sum up after this. Read all lines that include "TK", check index[0] for matches, if match sum up. 

修改。我这样做是为了排序列表。

提前致谢

EDIT2。由于人们在理解我时遇到问题,也许一些输出会有所帮助。 目前变量this打印:

Fam_c1_1        F       Extractions     02-0419 02-419TK        500     400     200000.0
Fam_c1_1        F       Extractions     5107    5107TK  1475    447.5   660062.5
Fam_c10_1       F       Extractions     5132    5132TK  1555    547.6   851518.0
Fam_c100_1      M       Extractions     5843    5843TK  2605    398.6   1038353.0
Fam_c1000_1     F       Extractions     9913    9913TK  1900    398     756200.0
Fam_c1001_1     F       Extractions     9512    9512TK  1050    20      21000.0

所以在这种情况下,我希望我的代码遍历列表,始终在内存中拥有列表的第一个值。如果它匹配下一行的第一个值,它将执行x。

1 个答案:

答案 0 :(得分:0)

我建议像这样使用......

with open('filename') as f:

   def lineValue(line):
     parts = line.split('\t')
     return float(parts[5]) * float(parts[6])

   def lineKey(line):
     parts = line.split('\t')
     return parts[0]

   for match, lines in groupby(
       line for line in f if "Fam" in line and "TK" in line,
       lineKey):
     yield sum(lineValue(line) for line in lines)

这种方式取决于所有匹配值已经相互跟随的事实。如果不是这种情况,itertools.groupby()将无济于事。当然,将线分割两次并不是最优雅的解决方案。

如果匹配的行不会相互跟随,则需要构建一个答案词典,然后defaultdict合理的声音:

result = defaultdict(float)
with open('filename') as f:

   def lineValue(line):
     parts = line.split('\t')
     return float(parts[5]) * float(parts[6])

   def lineKey(line):
     parts = line.split('\t')
     return parts[0]

   for line in f:
     if "Fam" in line and "TK" in line:
       result[lineKey(line)] += lineValue(line)

再次,将该线分开一次将是一个更优雅的解决方案。