python - 如何用特定集合中的元素填充 python 中的列表?

标签 python list random set combinations

如果我有一组表示列表元素可以采用的值的整数和给定长度的 python 列表。

我想用所有可能的组合填充列表。

示例

list length=3 and the my_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/

相关文章:

php - 如何在使用相同域的 NGINX 服务器上运行 django 和 wordpress?

python - 从 panda DataFrame 创建 pd.Series 列表

python - 如何将列表复制到另一个变量并保持该变量不可变?

python - 打印格式化的元组值

python - 使用 Python 将字符串粘贴到 Gnome 中选定的文本字段中

python - Boolean Python 值混淆

python - 使用 numpy 求和,其中 i != j

c - openssl RAND_load_file 总是返回 0

c - 为什么我总是用 rand() 得到相同的随机数序列?

C++ - 在范围内生成遵循正态分布的随机数