查找字串的所有不同排列,其中只允許排列某些索引。
例如string_perms('test_world', [2,3]) --> ['test_world', 'tets_world']
我有一個答案,但它看起來很臟。有沒有更優雅的方法來做到這一點?
from itertools import permutations
def string_perms(s, indices):
final = []
target = [let for ind,let in enumerate(s) if ind in indices]
perms = list(set(permutations(target)))
temp = list(s)
for perm in perms:
for ind,let in enumerate(perm):
temp[indices[ind]] = let
final.append(''.join(temp))
return final
uj5u.com熱心網友回復:
您可以使用具有串列推導式的迭代器:
import itertools as it
def string_perms(s, indices):
for _i in it.permutations([s[j] for j in indices], len(indices)):
i = iter(_i)
yield ''.join(a if j not in indices else next(i) for j, a in enumerate(s))
print(list(string_perms('test_world', [2,3])))
輸出:
['test_world', 'tets_world']
uj5u.com熱心網友回復:
一種變體,使用 numpy 直接索引。
import numpy as np
def string_perms(s, indices):
r = np.arange(len(s), dtype=int)
for p in list(permutations(indices)):
r[np.array(indices, dtype=int)] = p
yield ''.join(np.array(list(s))[r])
print(list(string_perms('test_world', [2,3])))
print(list(string_perms("azerty", [2,4,5])))
輸出:
['test_world', 'tets_world']
['azerty', 'azeryt', 'aztrey', 'aztrye', 'azyret', 'azyrte']
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/362740.html
