如何在列表理解中包含计数条件?

我创建了以下内容:


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 的方法。


如何在列表理解中包含计数条件?


慕妹3146593
浏览 170回答 2
2回答

素胚勾勒不出你

使用set可能有效。另一种选择是使用collections.Counter:from collections import Counterfrom itertools import productx =&nbsp; [&nbsp; &nbsp; &nbsp;comb for comb in product(range(5), repeat=4)&nbsp; &nbsp; &nbsp;if max(Counter(comb).values()) <= 2&nbsp; &nbsp; &nbsp;]

慕莱坞森

您可以创建一个生成器来生成元组,并使用以下命令检查您的条件Counter:from itertools import productfrom collections import Counterdef selected_tuples():&nbsp; &nbsp; for t in product(range(5), repeat=4):&nbsp; &nbsp; &nbsp; &nbsp; if Counter(t).most_common(1)[0][1]<=2:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; yield tprint(list(selected_tuples()))输出:[(0, 0, 1, 1), (0, 0, 1, 2), (0, 0, 1, 3), (0, 0, 1, 4), ...]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python