[英]How to check if the first half of a list is equal to the other efficiently?
I need to check if a Python list consists of two equal halves. 我需要检查Python列表是否包含两个相等的一半。 For example, this list does: 例如,此列表可以:
[6, 2, 0, 2, 3, 2, 6, 2, 0, 2, 3, 2]
and this doesn't 而这不是
[6, 2, 0, 2, 4, 6]
I've tried this check: len(lst) % 2 == 0 and lst[:len(lst)//2] == lst[len(lst)//2:]
but it seems to be too slow for bigger lists. 我试过这个检查: len(lst) % 2 == 0 and lst[:len(lst)//2] == lst[len(lst)//2:]
但是它似乎太慢了名单。 Any other solutions? 还有其他方法吗?
It's possible to do the check without creating the two sublists. 可以在不创建两个子列表的情况下进行检查。 It might be faster for really big lists. 真正的大型列表可能会更快。
n = len(lst)//2
all(lst[i]==lst[i+n] for i in range(n))
If you want to also check that your list is of even length, you could also add 如果您还要检查列表的长度是否均匀,您还可以添加
len(lst)%2==0
as a condition. 作为一个条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.