Python n个变量之间的相等性
如何在n个字符串的列表中找到最大数量的重复字符串,并在至少为j的情况下执行某些操作,而不写出所有可能的相等组合Python n个变量之间的相等性,python,Python,如何在n个字符串的列表中找到最大数量的重复字符串,并在至少为j的情况下执行某些操作,而不写出所有可能的相等组合 j = 3 ['123', '124', '123'] Desired output: FALSE becuase no element is repeated more than twice j = 3 ['123', '123', '123'] Desired output: TRUE because '123' is repeated three times j = 2 ['
j = 3
['123', '124', '123']
Desired output: FALSE becuase no element is repeated more than twice
j = 3
['123', '123', '123']
Desired output: TRUE because '123' is repeated three times
j = 2
['128', '128', '123']
Desired output: TRUE because '128' is repeated twice
如果将字符串放入列表中,可以使用注释中建议的
list.count()
方法,如下所示:
s_list = ['123', '123', '122']
def test_j(list_of_strings,j):
for s in list_of_strings:
if s_list.count(s) >= j:
return True
return False
print(test_j(s_list, 2))
您可以使用
collections.Counter
进行计数,然后检查max(Counter.values())
是否足够大。[vals.count(v)for v in vals]
将返回每个元素在列表中显示的次数。对于最后一个示例,它返回[3,3,1,3,1]
@piterbarg,当然它也在工作,但在O(n^2)时间内运行,而计数器在O(n)时间内创建。但在这种情况下,这很可能是无关紧要的:D@NiklasMertsch说得好!