Skip to main content
 首页 » 编程设计

python之从字母组合生成字符串的最佳选择是 python 还是 bash

2025年05月04日19EasonJim

我需要生成字符串 STA 和 STB。

STA 和 STB 是长度为 10 的字符串,每个只能包含字符 A,T,G 或 C。

我必须生成所有可能的 STA 组合,并根据 STA 生成 STB。

方式是字符 A 始终与 T 相关联,反之亦然,G 与 C 相关联,反之亦然。

所以可能的组合如下:

STA: ATGC... 
STB: TACG... 

或

STA: GTTA... 
STB: CAAT... 

等等。

我想知道使用 bash 或 python 执行此操作的最佳方法是什么

谢谢

请您参考如下方法:

虽然我不知道 bash 也不知道 permutations 会如何解决您的问题,但似乎 itertools.product 是一种相当简单的方法来做到这一点:

>>> s = 'atgc' 
>>> d = dict(zip(s, 'tacg')) 
>>> import itertools 
>>> for i in itertools.product(s, repeat=10): 
    sta = ''.join(i) 
    stb = ''.join(d[x] for x in i) 

虽然提议的方法在通过替换 'atgc' 字符串获得所有可能的排列方面是有效的,即找到 sta 字符串,找到 stb 不是通过字典查找更有效,而是通过翻译机制:

>>> trans = str.maketrans(s, 'tacg') 
>>> for i in itertools.product(s, repeat=10): 
    sta = ''.join(i) 
    stb = sta.translate(trans) 

感谢 Dave 强调更有效的解决方案。