[英]How to efficiently check the first list that have the concept in python
[英]How to check if the first half of a list is equal to the other efficiently?
我需要檢查Python列表是否包含兩個相等的一半。 例如,此列表可以:
[6, 2, 0, 2, 3, 2, 6, 2, 0, 2, 3, 2]
而這不是
[6, 2, 0, 2, 4, 6]
我試過這個檢查: len(lst) % 2 == 0 and lst[:len(lst)//2] == lst[len(lst)//2:]
但是它似乎太慢了名單。 還有其他方法嗎?
可以在不創建兩個子列表的情況下進行檢查。 真正的大型列表可能會更快。
n = len(lst)//2
all(lst[i]==lst[i+n] for i in range(n))
如果您還要檢查列表的長度是否均勻,您還可以添加
len(lst)%2==0
作為一個條件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.