我正在使用串列進行產品捆綁。這是清單:
list_id_category = ['c1'、'c2'、'c3'、'c4'、'c5'、'c6'、'c7'、'c8'、'c9'、'c10']
這是我需要的條件:
- 每個捆綁包含 3 個產品(例如:c1-c2-c3)
- 捆綁中不能只有一種類別(例如:c1-c1-c1 => 不允許)
- 每個捆綁可能有 2 個相同的類別(例如:c1-c1-c2)
- 每個捆綁的順序沒有區別(例如:c1-c2-c3 = c1-c3-c2 和很快)
這是我的代碼:
bundling_list = []
for i in list_id_category:
catefory1 = i
for j in list_id_category:
if j != i:
category2 = j
bundle = i '-' j
for k in list_id_category:
if i != k and j != k:
category3 = k
bundle = i '-' j '-' k
bundling_list.append(bundle)
但是我的代碼只是填充了 1,2,3 條件。它不滿足第四個條件。有誰知道如何修復它?謝謝你。
uj5u.com熱心網友回復:
您可以使用itertools.combinations_with_replacement(iterable, r)替換來構建所有組合的串列,然后過濾以洗掉相同元素重復 3 次的組合:
from itertools import combinations_with_replacement
list_id_category = ['c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'c10']
allbundlings = combinations_with_replacement(list_id_category, 3)
bundlings = [b for b in allbundlings if len(set(b)) > 1]
我者優先if len(set(b)) > 1,以if not (b[0] == b[1] and b[1] == b[2])概括
uj5u.com熱心網友回復:
以下生成器函式無需過度生成和過濾即可作業:
def combos(lst):
n = len(lst)
for i in range(n-1):
for j in range(i, n):
for k in range(max(i 1, j), n):
yield lst[i], lst[j], lst[k]
list(combos([1,2,3])]
# [(1, 1, 2), (1, 1, 3), (1, 2, 2), (1, 2, 3), (1, 3, 3), (2, 2, 3), (2, 3, 3)]
list(map("-".join, combos(['c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'c10'])))
# ['c1-c1-c2', 'c1-c1-c3', 'c1-c1-c4', 'c1-c1-c5', 'c1-c1-c6',
# 'c1-c1-c7', 'c1-c1-c8', 'c1-c1-c9', 'c1-c1-c10', 'c1-c2-c2',
# 'c1-c2-c3', ... , 'c9-c10-c10']
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/348109.html
上一篇:自定義類方法“不是函式”錯誤
