[英]How to get all strings of length=n from the characters in a list in python
I would like to know a simple and pythonic way to get all strings of length n that are composed of the characters contained in a list called L .我想知道一种简单且 Pythonic 的方法来获取所有长度为n 的字符串,这些字符串由名为L的列表中包含的字符组成。
For example:例如:
L = ['0','1']
n = 3
How do I get:如何得到:
['000','001','010','011','100','101','110','111']
A possible solution is by using itertools.product
.一个可能的解决方案是使用
itertools.product
。 It works, but it's not very elegant, so I'm looking for a more pythonic solution.它有效,但不是很优雅,所以我正在寻找一个更 Pythonic 的解决方案。 Here's how it would be:
这是它的样子:
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]
The resulting list looks like this:结果列表如下所示:
>>> x
['000', '001', '010', '011', '100', '101', '110', '111']
Is there something built-in like all_possible_strings(L, n)
, which takes the elements in L and obtains all possible combinations of length n with those elements?是否有像
all_possible_strings(L, n)
这样的内置all_possible_strings(L, n)
,它采用L 中的元素并获得长度为n 的所有可能的组合与这些元素?
The following code with Python 2.6 and above ONLY以下代码仅适用于 Python 2.6 及更高版本
First, import itertools:首先,导入itertools:
import itertools
Permutation (order matters):排列(顺序很重要):
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)]
Documentation:文档:
https://docs.python.org/2/library/itertools.html#itertools.permutations https://docs.python.org/2/library/itertools.html#itertools.permutations
Happy Coding快乐编码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.