简体   繁体   English

如何有效地检查列表的前半部分是否与另一部分相等?

[英]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.

相关问题 如何有效地检查 python 中具有概念的第一个列表 - How to efficiently check the first list that have the concept in python 如何有效地检查框列表是否相互重叠? - How to efficiently check if a list of boxes overlap with each other? 我怎样才能给这个列表的前半部分一个 A,给后半部分一个 B? - How can I give an A to first half of this list and a B to the second half? 如果列表中的元素数大于 2,则将列表前半部分中的 n 个元素与列表另一半中的元素组合 - Combine n elements in first half of list with elements in other half of a list, if number of elements in a list is greater than 2 如何将 dataframe 分成 2 个等份(前半行和后半行)- 在 Python - How to divide dataframe into 2 equal parts (first half rows and second half rows) - in Python 如何使用第一个值对列表列表进行排序,如果两者相等,则检查第二个,依此类推 - How to sort a list of list with the first value, if the both are equal check the second and so on 前一半与后一半的单列表轮换,包括奇数个元素 - Single list rotation of the first half with the other half, including odd number of elements 如何检查变量是否相等 - how to check if variables equal each other 如何有效地检查文件夹是否包含文件列表? - How to efficiently check if a folder contains a list of files? Python:如何有效地检查项目是否在列表中? - Python: how to check that if an item is in a list efficiently?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM