我创建了以下内容:
from itertools import product
x = [(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 的方法。
如何在列表理解中包含计数条件?
素胚勾勒不出你
慕莱坞森
相关分类