【发布时间】:2019-12-17 12:31:47
【问题描述】:
我已在此处 (https://scipher.wordpress.com/2010/12/02/simple-sliding-window-iterator-in-python/) 调整了滑动窗口生成器功能以满足我的需要。这是我第一次使用生成器函数,所以我做了很多背景阅读。鉴于我(仍然)有限的经验,我正在就以下问题征求建议:
下面的代码是这样做的:我使用滑动窗口函数在大约 250 个字符的窗口中迭代一个 5,500 个字符的字符串(约 5,500 bp 的 DNA 序列),步长为 1。对于每个块,我将其 GC 内容与 750 行文件中的一行进行比较。 (GC 内容是等于 G 或 C 的字符串元素的百分比)。
但是,对于我的下游用途,我真的很想随机循环这些块。从我的 Stack Overflow 搜索中,我了解到无法对生成器对象进行混洗,并且我无法在函数内混洗窗口,因为它实际上一次搜索一个窗口,返回到下一个块的函数,因为那个“产量”。 (如果我误解了,请纠正我)。
目前,我的代码看起来像这样(当然,使用上面链接中的生成器函数):
with open('/pathtofile/file.txt') as f:
for line in f:
line = line.rstrip()
# For each target, grab target length (7), gc content (8)
targ_length = line.split("\t")[8]
gc = int(line.split("\t")[7])
# Window size = amplicon length minus length of fwd and rev primers
# Use a sliding window function to go along "my_seq" (5,500bp sequence). Check GC content for each window.
chunks = slidingWindow(my_seq, targ_length, step=1)
found = 0
for i in chunks:
# When GC content = same as file, save this window as the pos ctrl fragment & add primers to it
dna_list = list(i)
gc_count = dna_list.count("G") + dna_list.count("C")
gc_frac = int((gc_count / len(dna_list)) * 100)
# if (gc - 5) < gc_frac < (gc + 5):
if gc_frac == gc:
found = 1
# Store this piece
break
if found == 0:
# Store some info to look up later
有人对最佳方法有想法吗?对我来说,最明显的(也基于 Stack Overflow 搜索)是在没有生成器函数的情况下重写它。我担心在包含大约 5,251 个元素的列表上循环 750 次。我可以做?生成器似乎是我想做的一个优雅的解决方案,除了现在我决定要随机化块顺序。显然我需要牺牲效率来做到这一点,但我想知道更有经验的编码人员是否有一些聪明的解决方案。谢谢!
【问题讨论】:
标签: python random generator shuffle sliding-window