我創建了以下內容:from itertools import productx = [(b0, b1, b2, b3) for b0, b1, b2, b3 in product(range(5), repeat=4)]這將創建從[0,0,0,0]到的所有元組[4,4,4,4]。我想作為一個條件,只包含那些重復次數不超過 2 次的元組。所以我想忽略這樣的元組,[2,2,2,1]或者[3,3,3,3]同時保持元組,例如[0,0,1,2]或[1,3,4,2]我嘗試了以下方法,我認為還可以,但看起來很麻煩。y = [(b0, b1, b2, b3) for b0, b1, b2, b3 in product(range(5), repeat=4) if (b0, b1, b2, b3).count(0)<=2 and (b0, b1, b2, b3).count(1)<=2 and (b0, b1, b2, b3).count(2)<=2 and (b0, b1, b2, b3).count(3)<=2 and (b0, b1, b2, b3).count(4)<=2]也許是一種計算每個元素[0,1,2,3,4]并取其最大值并聲明 max<=2 的方法。如何在列表理解中包含計數條件?
2 回答

素胚勾勒不出你
TA貢獻1827條經驗 獲得超9個贊
使用set可能有效。另一種選擇是使用collections.Counter:
from collections import Counter
from itertools import product
x = [
comb for comb in product(range(5), repeat=4)
if max(Counter(comb).values()) <= 2
]

慕萊塢森
TA貢獻1810條經驗 獲得超4個贊
您可以創建一個生成器來生成元組,并使用以下命令檢查您的條件Counter:
from itertools import product
from collections import Counter
def selected_tuples():
for t in product(range(5), repeat=4):
if Counter(t).most_common(1)[0][1]<=2:
yield t
print(list(selected_tuples()))
輸出:
[(0, 0, 1, 1), (0, 0, 1, 2), (0, 0, 1, 3), (0, 0, 1, 4), ...]
添加回答
舉報
0/150
提交
取消