如何在python中使用特定集合中的元素填充列表?
如果我有一组整数,它们表示列表元素可以接受的值和给定长度的python列表 我想用所有可能的组合来填充列表 示例 列表如何在python中使用特定集合中的元素填充列表?,python,list,random,set,combinations,Python,List,Random,Set,Combinations,如果我有一组整数,它们表示列表元素可以接受的值和给定长度的python列表 我想用所有可能的组合来填充列表 示例 列表length=3和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
length=3
和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中,它返回一个迭代器,作为一种更有效的方法,您可以使用列表理解):
在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]]
>>>
这就是
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中,它返回一个迭代器,作为一种更有效的方法,您可以使用列表理解):
在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]]
>>>
使用:
list()
调用是可选的;如果元组而不是列表可以,那么result=list(product(my_set,repeat=length))
就足够了
演示:
random.sample()
提供给定输入序列的随机子集;它不会产生所有可能的值组合。使用:
lst_length = 3
my_set = {1,-1}
result = [[x] for x in my_set]
for i in range(1,lst_length):
temp = []
for candidate in my_set:
for item in result:
new_item = [candidate]
new_item += item
temp.append(new_item)
result = temp
print result
list()
调用是可选的;如果元组而不是列表可以,那么result=list(product(my_set,repeat=length))
就足够了
演示:
random.sample()
提供给定输入序列的随机子集;它不会产生所有可能的值组合
lst_length = 3
my_set = {1,-1}
result = [[x] for x in my_set]
for i in range(1,lst_length):
temp = []
for candidate in my_set:
for item in result:
new_item = [candidate]
new_item += item
temp.append(new_item)
result = temp
print result
如果列表长度为1,则结果是其元素等于集合的列表。每当列表长度增加1时,可以通过将集合的每个元素追加到结果列表中来获得结果
如果列表长度为1,则结果是其元素等于集合的列表。每次列表长度增加1,都可以通过将集合的每个元素附加到结果列表中来获得结果。正是我想要的。正是我想要的。