python

时间:2018-01-13 14:00:10

标签: python performance pop fasta subsampling

我设计了一个编辑了一个小脚本,从原始文件中对x行进行二次采样。原始文件是fasta,每个序列有两行,程序提取那些x个序列(两行一起)。 这是它的外观:

#!/usr/bin/env python3
import random
import sys
# How many random sequences do you want?
num = int(input("Enter number of random sequences to select:\n"))

# Import arguments
infile = open(sys.argv[1], "r")
outfile = open(sys.argv[2], "w")

# Define lists
fNames = []
fSeqs = []
# Extract fasta file into the two lists
for line in infile:
    if line.startswith(">"):
        fNames.append(line.rstrip())
    else:
        fSeqs.append(line.rstrip())

# Print total number of sequences in the original file
print("There are "+str(len(fNames))+" in the input file")

# Take random items out of the list for the total number of samples required
for j in range(num):
    a = random.randint(0, (len(fNames)-1))
    print(fNames.pop(a), file = outfile)
    print(fSeqs.pop(a), file = outfile)

infile.close()
outfile.close()
input("Done.")

创建具有ID和核苷酸(分别为第1行和第2行)的列表非常快,但打印输出需要永远。提取的数字最多可达2M,但从10000开始变慢。

我想知道是否有办法让它更快。 .pop是问题吗?如果我首先创建一个随机的唯一数字列表然后提取它们会更快吗?

最后,打印“完成”后,终端不会返回“正常完成状态”。同时我不知道为什么。使用我的所有其他脚本,我可以在完成后立即输入。

1 个答案:

答案 0 :(得分:0)

random.sample(在评论中提出)和字典使脚本更快。 这是最后的脚本:

#!/usr/bin/env python3
import random
import sys
# How many random sequences do you want?
num = int(input("Enter number of random sequences to select:\n"))

# Import arguments
infile = open(sys.argv[1], "r")
outfile = open(sys.argv[2], "w")

# Define list and dicctionary
fNames = []
dicfasta = {}
# Extract fasta file into the two lists
for line in infile:
    if line.startswith(">"):
        fNames.append(line.rstrip())
        Id = line.rstrip()
    else:
        dicfasta[Id] = line.rstrip()

# Print total number of sequences in the original file
print("There are "+str(len(fNames))+" in the input file")

# Create subsamples
subsample = []
subsample = random.sample(fNames, num)

# Take random items out of the list for the total number of samples required
for j in subsample:
    print(j, file = outfile)
    print(dicfasta[j], file = outfile)

infile.close()
outfile.close()
input("Done.")