gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:20:29 24 4
gpt4 key购买 nike

如果我有一组表示列表元素可以采用的值的整数和给定长度的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com