Skip to main content
 首页 » 编程设计

Python之使用 Numpy、ValueError 生成随机 dna 序列

2025年05月04日14cmt

有两个问题我想问任何熟悉 numpy 的人。我见过非常相似的问题(和答案),但没有一个使用我想使用的 numpy,因为它提供了很多我将来可能想在该代码中使用的其他选项。 我试图在 python 中使用“随机”生成随机核苷酸序列列表。因为我想要非均匀概率,所以我决定改用 numpy。但是,我收到错误消息:“ValueError:a 必须是一维或整数”。

import numpy as np 
 
def random_dna_sequence(length): 
    return ''.join(np.random.choice('ACTG') for _ in range(length)) 
 
with open('dna.txt', 'w+') as txtout: 
    for _ in range(10): 
        dna = random_dna_sequence(100) 
        txtout.write(dna) 
        txtout.write("\n") 
 
        print (dna) 

我是一个彻头彻尾的磨砂膏,我无法弄清楚多维性在哪里或如何发挥作用。我怀疑“.join()”,但我不确定也不确定如何替换它。 我的另一个问题是如何获得非均匀概率。我尝试使用“np.random.choice('ACTG', p=0.2, 0.2, 0.3, 0.3)”但它不起作用。

我希望有人能提供帮助。提前致谢。

问候, 伯特

请您参考如下方法:

对于问题的第一部分,将 a 作为列表传递:

def random_dna_sequence(length): 
    return ''.join(np.random.choice(list('ACTG')) for _ in range(length)) 

或者将您的基定义为列表或元组:

BASES = ('A', 'C', 'T', 'G') 
 
def random_dna_sequence(length): 
    return ''.join(np.random.choice(BASES) for _ in range(length)) 

第二部分有类似的解决方案:将概率作为列表或元组传递:

BASES = ('A', 'C', 'T', 'G') 
P = (0.2, 0.2, 0.3, 0.3) 
 
def random_dna_sequence(length): 
    return ''.join(np.random.choice(BASES, p=P) for _ in range(length))