[英]Fast way to check two lists for consistency
I need to check two lists for consistency, eg to return True
if the first list dosen't contain elements, which are not present in second list, and if the count
of similar elements is the same. 我需要检查两个列表的一致性,例如,如果第一个列表不包含第二个列表中不存在的元素,并且相似元素的
count
相同,则返回True
。 By now, I came out with following: 现在,我得出以下结论:
def is_consistent(spec_a, spec_b):
for a in spec_a:
if spec_a.count(a) != spec_b.count(a):
return False
return True
But I need to do it in a loop, so I wonder, can it be faster? 但是我需要循环执行,所以我想知道,它会更快吗?
If I'm understanding the question properly, perhaps you could use a Counter
: 如果我对问题的理解正确,也许您可以使用
Counter
:
from collections import Counter
def is_consistent(spec_a, spec_b):
c1 = Counter(spec_a)
c2 = Counter(spec_b)
result = c1 - c2
return all(result[key] == 0 for key in c1)
The loop is unavoidable -- It will always be there in some form or another. 循环是不可避免的-它将始终以某种形式存在。 In fact, I have 3 loops here.
实际上,我在这里有3个循环。 (one in each
Counter
and then the most obvious one at the end). (每个
Counter
一个,最后一个最明显)。 However, the operation that my solution avoids is the .count
which is another implicit loop nested inside another loop. 但是,我的解决方案避免的操作是
.count
,这是嵌套在另一个循环中的另一个隐式循环。
Nested loops are generally the ones you want to eliminate because if the outer loop iterates N times and the inner loop iterates N times than you have a total of N*N iterations. 嵌套循环通常是您要消除的循环,因为如果外循环迭代N次,而内循环迭代N次,则您总共要进行N * N次迭代。 Compare that to my solution which has only ~3*N iterations (3 loops with about N iterations each).
将该解决方案与我的解决方案进行比较,该解决方案只有约3 * N次迭代(3个循环,每个循环约N次迭代)。 If
N
is big, you can see how this would lead to a large number of operations being saved. 如果
N
大,您将看到这将如何导致大量操作被保存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.