如果我有一组表示列表元素可以采用的值的整数和给定长度的 python 列表。
我想用所有可能的组合填充列表。
示例
list
length=3
and themy_set ={1,-1}
可能的组合
[1,1,1],[1,1,-1],[1,-1,1],[1,-1,-1],
[-1,1,1],[-1,1,-1],[-1,-1,1],[-1,-1,-1]
我尝试使用随机类中的 random.sample 方法 但它没有帮助。我做了:
my_set=[1,-1]
from random import sample as sm
print sm(my_set,1) #Outputs: -1,-1,1,1 and so on..(random)
print sm(my_set,length_I_require) #Outputs**:Error
最佳答案
这就是 itertools.product
的用途:
>>> from itertools import product
>>> list(product({1,-1},repeat=3))
[(1, 1, 1), (1, 1, -1), (1, -1, 1), (1, -1, -1), (-1, 1, 1), (-1, 1, -1), (-1, -1, 1), (-1, -1, -1)]
>>>
如果你想要结果作为列表,你可以使用 map
将元组的迭代器转换为 list if list(在 python3 中它返回一个迭代器,这是一种更有效的方式,你可以使用列表理解):
>>> map(list,product({1,-1},repeat=3))
[[1, 1, 1], [1, 1, -1], [1, -1, 1], [1, -1, -1], [-1, 1, 1], [-1, 1, -1], [-1, -1, 1], [-1, -1, -1]]
在 python3 中:
>>> [list(pro) for pro in product({1,-1},repeat=3)]
[[1, 1, 1], [1, 1, -1], [1, -1, 1], [1, -1, -1], [-1, 1, 1], [-1, 1, -1], [-1, -1, 1], [-1, -1, -1]]
>>>
关于python - 如何用特定集合中的元素填充 python 中的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32550447/