按索引排列字符串
Permute string by indices
查找字符串的所有不同排列,其中只允许排列某些索引。
例如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
您可以使用具有列表理解的迭代器:
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']
一个变体,使用 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']
查找字符串的所有不同排列,其中只允许排列某些索引。
例如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
您可以使用具有列表理解的迭代器:
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']
一个变体,使用 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']