Python3:字符串列表,其中字符串具有可变字母(并非所有位置都是字母)

时间:2017-11-09 09:52:51

标签: python string python-3.x replace

首先是一些生物学背景,所以你理解我的问题。在生物学中,DNA序列可以含有被酶或蛋白质识别的基序。这些主题是字符串,如“GACTGC”。分析可以揭示,图案中的位置是否“保守”。

酶可能最好地识别“GACTGC”,但也可能识别“CACTGC”甚至“TTCTGC”。所以,有些职位可能会有所不同。

我有以下情况: 我想创建一个可以识别的带有图案的排列列表。为了做到这一点,我有信息:

最佳认可:GACTGC

基地,也是可能的:

GACTGC
A  C G
T    A

这意味着,在第一个位置,也可能是A或T,在第4个位置可能有C等,但在第2个位置,A是守恒的,没有别的可能。

我可以通过将“最适合”的主题转换为字母列表并替换一个字母,加入并附加到我的列表(为每个位置执行此操作)来生成一个列表,其中每个位置的基数不同。所以它基本上是硬编码的。 它成功了,因为我改变了任何位置,无论输入什么主题。 但现在我想根据主题将特定位置更改为特定字母并存储特定排列。

所以,我正在寻找最短/最快/最聪明的方式,传递位置及其有效字母的信息,以及如何为一个和两个变量位置创建排列。

请注意:我会尝试在答案中或通过编辑发布我的代码,以某种方式复制粘贴然后ctrl + k对标记的代码不起作用

1 个答案:

答案 0 :(得分:1)

使用itertools可能有办法解决这个问题,但我认为可以用自制的排列函数快速完成:

example_bases = [
  "GAT",  # options for first position
  "A",    # options for second position
  "C",    # ...
  "TC",
  "G",
  "CGA"
]

def permutate(bases, results, depth=0, current_result=""):
"""Create permutations of a list of strings

All resulting strings have the length len(bases), and there will be a total
of mult([len(options) for option in bases]) total results, e.g.:
["abc", "de", "fghi"] -> 3 * 2 * 4 -> 24

:param bases: List of possible options for a base
:param results: The object which will contain all valid results
:param depth: Internal counter for current recursive depth 
:param current_result: Internal variable to keep track of progress 
"""
  if depth == len(bases):
    results.append(current_result)
  else:
    for base in bases[depth]:
      permutate(bases, results, depth+1, current_result+base)

example_results = []
permutate(example_bases, example_results)
for sequence in example_results:
  print(sequence)

打印此特定示例的18种可能组合:

GACTGC
GACTGG
GACTGA
GACCGC
GACCGG
GACCGA
AACTGC
AACTGG
AACTGA
AACCGC
AACCGG
AACCGA
TACTGC
TACTGG
TACTGA
TACCGC
TACCGG
TACCGA

如果递归不属于您的问题,或者您对代码有疑问,请随时提出。

相关问题