[英]Are all lists in a list equal
Is there a preferred general solution for testing equality of a list of lists. 是否有用于测试列表列表是否相等的首选通用解决方案。 I'm attempting the apply this example more generally to a list of lists.
我正在尝试将此示例更广泛地应用于列表列表。 I currently have the following solution, where
_list
is a generic list of unknown length/number of elements. 我目前有以下解决方案,其中
_list
是未知长度/元素数的通用列表。
all(x == y for x, y in zip(_list, _list[1:]))
or if the order doesn't matter. 还是顺序无关紧要。
all([sorted(x) == sorted(y) for x, y in zip(_list, _list[1:])])
Beyond checking neighbouring lists for equality, how can/should this approach my improved? 除了检查相邻列表是否相等之外,如何/应该改善这种方法?
I believe, simple and fast enough way would be 我相信,足够简单和快速的方法是
all(a[0] == ax for ax in a)
You don't need to compare all elements pairwise, short route is to compare 1 vs all others. 您无需成对比较所有元素,捷径就是比较1与所有其他元素。 And in reality, better to compare against all (
ax in a
) instead of "against others" ( ax in a[1:]
), as slicing is most probably more computation-intensive that single comparison. 实际上,最好是与所有对象(a中的
ax in a
)进行比较,而不是“针对其他对象”( ax in a[1:]
)进行比较,因为切片可能比单个比较的计算量更大。 Depends on your data, tho, but in general I'd suggest not bothering. 视您的数据而定,但总的来说,我建议您不要打扰。
use sorted build in function: for example if you have two list x and y then compare like: sorted(x)==sorted(y) 使用已排序的内置函数:例如,如果您有两个列表x和y,则进行如下比较:sorted(x)== sorted(y)
list1 = [7,9,8]
list2 = [8,7,9]
sorted(list1)==sorted(list2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.