如何在列表推导中包括计数条件?

时间:2019-03-28 20:55:13

标签: python list-comprehension

我创建了以下内容:

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

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

2 个答案:

答案 0 :(得分:4)

使用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
     ]

答案 1 :(得分:2)

您可以创建一个生成器来生成元组,并使用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), ...]
相关问题