我需要找到一个更快的方法来找到一个8-11字符串的互换,以下列方式单一的交换:上的绳子
给定一个字符串'STDILGNLYE'
,找到所有的字母一个字母互换:
list_AA = ['A', 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H', 'I', 'L', 'K', 'M',
'F', 'P', 'S', 'T', 'W', 'Y', 'V']
即,对于字符串中的每个字母,替换原字符串中的每个字母有一个在list_aa
。输出将是:
ATDILGNLYE
RTDILGNLYE
NTDILGNLYE
...
SADILGNLYE
SRDILGNLYE
SNDILGNLYE
...
...
STDILGNLYV
对于总共200个新字符串(每个位置在字符串中每个位置20个交换)。 我有什么至今:需要
def _create_swaps(original_str):
list_peps = []
for i in range(len(original_str)):
for k in range(len(list_AA)):
list_peps.append(_insert_aa(original_str, i, list_aa[k]))
#remove original string
return [i for i in list_peps if i != original_str]
def _insert_aa(string, index, aa):
list_string_elements = list(string)
del list_string_elements[index]
hash_string.insert(index, aa)
return "".join(hash_string)
因为这需要重复〜10 ** 6倍,这是一个大项目最慢的一步。有没有办法以更快的方式找到这样的交换(通过消除"".join
,插入,步骤/通过找到交换)?
参考:
ncalls tottime percall cumtime percall filename:lineno(function)
185275200 330.286 0.000 429.295 0.000 models.py:233(_insert_aa)
975240 147.322 0.000 616.979 0.001 models.py:225(_create_swaps)
185280201/185280197 59.137 0.000 59.138 0.000 {method 'join' of 'str' objects}
185275208 39.875 0.000 39.875 0.000 {method 'insert' of 'list' objects}
975240 21.027 0.000 21.027 0.000 models.py:231(<listcomp>)
186746064 18.516 0.000 18.516 0.000 {method 'append' of 'list' objects}
你需要发出的所有生成的字符串,或者只是指望他们? – Steve
@Steve我需要所有的字符串。正如你从'_create_swaps'的返回调用中看到的那样,它会返回除原始字符串之外的所有创建的字符串。 –
您可能想尝试找出一种方法,用'map()'替换其中一个操作...参见[本文](https://www.python.org/doc/essays/list2str/)循环效率...当然,性能总是比理论好,尽管... –