快速高效的方法做滑动窗口的整个长度Fi

2024-04-20 12:45:05 发布

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

我有一个制表符分隔的文件,其中包含大约2207行,其中有4列float或int类型,如图所示以下:在

Id    pos    value1    value2
01    1123   0.76483   0.9001
02    1124   0.20      0.9800

另一个文件要与之比较,它包含大约27041行和4列:

^{pr2}$

现在,我的目标是找到所有可能的连续3行或更高行,其中

  1. 它们在第一个文件(Id)的第一列的内容等于第二个文件(Id)的第二列。在
  2. 它们在第一个文件的第二列(pos)的内容在第二个文件的第3列和第4列之间。在

我的方法是:

  1. 通过一个长度为3的滑动窗口循环到第一个文件的整个行数(这是我的外部循环)
  2. 第二个循环是迭代并以滑动窗口的每个元素为例,比如3,然后
  3. 检查该元素是否满足上述条件(如果满足),然后中断循环以获取第一个文件的下一个元素
  4. 否则,继续搜索第二个文件以找到目标

对于长度为300行的第一个文件,整个滑动窗口检查第二个文件大约需要5分钟。然而,我正在寻找一种更快更有效的方法来做到这一点。在

下面是一个令人满意的结果的例子,假设我们执行了长度为3的窗口滑动:

从文件1:

idW = (01,01,01)
posW = (127, 192,199)
val1W = (.9,.01,.23)
val2W = (.2,.03,.43)

从文件2:

name    Id    pos1    pos2
s13e    01    120     200

为了满足要求,必须满足以下要求: 第一个文件的posW介于file2的pos1和pos2的值之间:

连续3行(true)

file1的Id等于file2(true)

posW介于pos1和pos2的值之间(true)

由于以上条件均为真且满足,故结果满足

代码片段如下:

# borrowed from one answer from stack overflow 
def sliding_window (s, n):
 it = iter(seq)
 result = tuple(islice(it, n))
 if len(result) == n:
    yield result
 for elem in it:
    result = result[1:] + (elem,)
    yield result

Ids, pos, val1, val2 = zip(*Data)
# len_Data is the entire length of the file 
for windwCounts in range(3,len_Data):
    file2count = 0
    swindow_id = sliding_window(Ids, windwCounts)
    swindow_pos = sliding_window(pos, windwCounts)
    swindow_val1 = sliding_window(val1, windwCounts)
    swindow_val2 = sliding_window(val2, windwCounts)
    slidingWindws = zip(swindow_id, swindow_pos,
                        swindow_val1, swindow_val2)
    for idW, posW, val1W, val2W in slidingWindws:
     while (file2count <= len_file2):
            name,id2,pos1,pos2 = file2[file2count]
            # No point of moving down if the pos of file1 is less than pos2 of file2
            if any(int(ps) < pos2 for ps in posW):
                    break
            # All conditions must be met:-
            ids_cond = all(a_id == id2 for a_id in idW)
            within_data = all(pos1 <= int(ps) <= pos2
                                       for ps in posW)
            if ids_cond and within_data:

                  print "satisfy"
                  break 

            else:
                  print "not satisfy"
            genesCounts += 1

提前谢谢,真的很感谢你的帮助!!!在


Tags: 文件inposidforifresultwindow