**我怎样才能将这一行缩短为一两个动作? ** s.count('1') < 5 and s.count('2') < 5 and s.count('3') < 5 and s.count('4') < 5 and s.count('5') < 5 and s.count('6') < 5 and s.count('7') < 5 and s.count('8') < 5: condition: it is necessary to check that no digit in the number is contained more than 4 times
我正在考虑对每个数字进行某种迭代,并将其与 5 进行比较。也许通过范围
all()
,仅当 iterable 中的所有元素都是 True
时才返回 True
:
s = '123455556789'
result = all(s.count(i) < 5 for i in '1234567890')
类似的东西
from collections import Counter
all(x <= 4 for x in Counter(s).values())
每次调用
s.count
都必须遍历整个字符串,而 Counter(s)
只需要遍历字符串一次。