【问题标题】:How to get all strings of length=n from the characters in a list in python如何从python列表中的字符中获取长度= n的所有字符串
【发布时间】:2021-09-27 03:44:28
【问题描述】:

我想知道一种简单且 Python 的方法来获取所有长度为 n 的字符串,这些字符串由名为 L 的列表中包含的字符组成。

例如:

L = ['0','1']
n = 3

我如何获得:

['000','001','010','011','100','101','110','111']

一个可能的解决方案是使用itertools.product。它可以工作,但不是很优雅,所以我正在寻找一个更 Pythonic 的解决方案。 它是这样的:

L = ['0','1']
n = 3
a = [L for i in range(0,n)]
x = list(itertools.product(*a))
x = ["".join(i) for i in x]

结果列表如下所示:

>>> x
['000', '001', '010', '011', '100', '101', '110', '111']

有没有像all_possible_strings(L, n) 这样的内置东西,它获取L 中的元素并获得所有可能的长度n 与这些元素的组合?

【问题讨论】:

    标签: python-3.x list character combinations permutation


    【解决方案1】:

    使用product 的重复选项似乎可以更直接地为您提供您想要的:

    L = ['0','1']
    n = 3
    x = list(itertools.product(L, repeat=n))
    x = ["".join(i) for i in x]
    print(x)
    

    输出:

    ['000', '001', '010', '011', '100', '101', '110', '111']
    

    【讨论】:

      【解决方案2】:

      以下代码仅适用于 Python 2.6 及更高版本

      首先,导入 itertools:

      import itertools
      

      排列(顺序很重要):

      print list(itertools.permutations([1,2,3,4], 2))
      [(1, 2), (1, 3), (1, 4),
      (2, 1), (2, 3), (2, 4),
      (3, 1), (3, 2), (3, 4),
      (4, 1), (4, 2), (4, 3)]
      

      文档:

      https://docs.python.org/2/library/itertools.html#itertools.permutations

      快乐编码

      【讨论】:

      • 这并不适合我的情况,尽管这是一个很好的建议。就我而言,Ln 短(即我的列表中有 2 个元素,但我想要长度为 3 的字符串)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-21
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多