[英]How to create in a 2-dimentionals array all combinations from 2 different array
我必須創建一個如下所示的多維列表:
[[[1,R],[1,R]],[[1,B],[1,B]],[[2,R],[1,B]],[[2,R],[2,B]]]...
從兩個列表:
[1,2]
和[R,B]
我的目標是創建所有可能的組合。
我做了一些有效的事情。 有一段時間,但是當組合的數量很大時,它會花費很多時間。 例如,當我有 n(它是顏色數)= 5 並且 N = 6 --> RandomedColor= [Red,white,black,green,Yellow] and liste2 = [1,2,3,4,5, 6]至少需要5分鍾才能完成。
def Create_All_list_from_n(N): #Create all possible combinations of numbers with colors. if n = 2, and N = 5 then, there will be 2**5 combinations.
all_list_of_N = []
while(len(all_list_of_N) != n**N):
current_list = []
for i in range(1,N+1):
current_list.append([random.choice(RandomedColors),i])
if current_list not in all_list_of_N:
all_list_of_N.append(current_list)
print(all_list_of_N)
print(len(all_list_of_N))
return all_list_of_N
感謝您的幫助!
這可以使用itertools.product()
相對有效地實現。
例如:
import itertools
print(list(itertools.product([1, 2], ['R', 'B'])))
# [(1, 'R'), (1, 'B'), (2, 'R'), (2, 'B')]
然后你可以用它來生成你需要的副本。
您可以使用itertools
中的product
和combinations_with_replacement
from itertools import product, combinations_with_replacement
x = [1,2]
y = ['R','B']
products = [list(i) for i in product(x,y)]
print([list(i) for i in combinations_with_replacement(products,2)])
Output:
[[[1, 'R'], [1, 'R']], [[1, 'R'], [1, 'B']], [[1, 'R'], [2, 'R']], [[1, 'R'], [2, 'B']], [[1, 'B'], [1, 'B']], [[1, 'B'], [2, 'R']], [[1, 'B'], [2, 'B']], [[2, 'R'], [2, 'R']], [[2, 'R'], [2, 'B']], [[2, 'B'], [2, 'B']]]
要處理組合問題, itertools
非常有用。 它提供了生成組合所需的所有 function。
這個想法是先使用product
然后再combinations_with_replacement
。
L1 = [1,2]
L2 = ["R" ,"B"]
import itertools
products = list(itertools.product(L1, L2))
combinations = list(itertools.combinations_with_replacement(products, 2))
Output:
[((1, 'R'), (1, 'R')),
((1, 'R'), (1, 'B')),
((1, 'R'), (2, 'R')),
((1, 'R'), (2, 'B')),
((1, 'B'), (1, 'B')),
((1, 'B'), (2, 'R')),
((1, 'B'), (2, 'B')),
((2, 'R'), (2, 'R')),
((2, 'R'), (2, 'B')),
((2, 'B'), (2, 'B'))]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.