各位大神:
本人想解決的問題是:求組合結果。比如:有這么一個串列:[[1, 2], [3, 4], [5,6]]
組合后結果是:[[1, 3, 5], [1, 3, 6],[1, 4, 5], [1, 4, 6],[2, 3, 5], [2, 3, 6],[2, 4, 5], [2, 4, 6],]
請教有什么好的方法和思路?
我的代碼如下:
import copy
data = ([randint(1,9) for i in range(randint(2,3))] for j in range(4))
def run(data):
result = []
list0 = next(data)
list1 = next(data)
for i in list0:
for j in list1:
result.append([i,j])
while True:
try :
list1 = next(data)
except:
break
count = len(list1)
resultCount = len(result)
temp = copy.deepcopy(result)
for i in range(count-1):
for j in temp:
result.append(j)
for j in range(count):
for i in range(len(result)):
if j == int(i/resultCount):
result[i].append(list1[j])
return result
time0 = time.time()
print(run(data))
time1 = time.time()
print(time1-time0)
uj5u.com熱心網友回復:
import itertools as it
from random import randint
data = [[randint(1,9) for i in range(randint(2,3))] for j in range(4)]
e = it.product(*data)
print(list(e))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/269918.html
上一篇:python爬取東方財富網深滬股通成交top10頁面核心資料爬不了
下一篇:python畫激光炮
