Python 如何在列表中包含计数条件?
我创建了以下内容:Python 如何在列表中包含计数条件?,python,list-comprehension,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] 我尝试了以下方法,我认为这是可以的,但它似乎
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]
y=[(b0,b1,b2,b3)对于产品中的b0,b1,b2,b3(范围(5),重复=4)如果(b0,b1,b2,b3)。使用set
计数(0)可能有效。另一个选项是使用集合。计数器
:
from collections import Counter
from itertools import product
x = [
comb for comb in product(range(5), repeat=4)
if max(Counter(comb).values()) <= 2
]
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()))
从集合导入计数器
来自itertools进口产品
x=[
产品中梳子的梳子(范围(5),重复=4)
如果max(Counter(comb).values())您可以创建一个生成器来生成元组,并使用计数器检查您的条件:
from collections import Counter
from itertools import product
x = [
comb for comb in product(range(5), repeat=4)
if max(Counter(comb).values()) <= 2
]
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()))
如果len(set(t))>2,那么x=[t代表产品中的t(范围(5),repeat=4)如何?
是的,这似乎更像是我在想的。在测试您的解决方案时,我注意到我在原始代码中遗漏了一个案例(现在已更正)。非常感谢。虽然我确实喜欢生成器,但我认为在这里使用它们有点过分,当然这取决于最终代码的使用位置。