【问题标题】:Permute string by indices按索引排列字符串
【发布时间】:2021-11-19 19:41:02
【问题描述】:

查找字符串的所有不同排列,其中仅允许排列某些索引。

例如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

【问题讨论】:

    标签: python string permutation itertools


    【解决方案1】:

    您可以使用带有列表推导式的迭代器:

    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']
    

    【讨论】:

      【解决方案2】:

      一个变种,使用 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']
      

      【讨论】:

        猜你喜欢
        • 2014-07-02
        • 2012-06-06
        • 1970-01-01
        • 1970-01-01
        • 2012-06-29
        • 2019-04-29
        • 2019-03-22
        • 1970-01-01
        相关资源
        最近更新 更多