我创建了以下内容: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
提交
取消