简体   繁体   English

如何检查列表中的所有元素是否相同?

[英]How can I check if all the elements in a list are the same?

There is a list, whose items are either integers or string NULL . 有一个列表,其项目为整数或字符串NULL How can I check if the list is all NULL , without checking each item in the list using a loop? 如何检查列表是否全部为NULL而不使用循环检查列表中的每个项目?

Convert the list to a set and compare it like this 将列表转换为集合,然后像这样进行比较

>>> set(["NULL", "NULL"]) == {"NULL"}
True
>>> set(["NULL", "NULL", 1]) == {"NULL"}
False

When you convert your list to a set , all the duplicates are removed and only the unique values are retained. 当您将列表转换为set ,所有重复项都将被删除,并且仅保留唯一值。 Now, you can compare it against another set with just NULL . 现在,您可以将其与另一个仅有NULL集合进行比较。 They both are equal, then your actual list has only NULL s. 它们都是相等的,那么您的实际列表只有NULL

Note: Converting to set will only work if all the items in your list are hashable. 注意:仅当列表中的所有项目都是可哈希的时,才转换为set In your case, you have only numbers and strings. 就您而言,只有数字和字符串。 So, you are fine here. 所以,你很好。


Alternate, and the idiomatic, way would be to use all function (or its sister function any ) 另一种惯用的方式是使用all功能(或其any姊妹功能)

>>> all(item == "NULL" for item in ["NULL", "NULL", 1])
False
>>> all(item == "NULL" for item in ["NULL", "NULL"])
True

Here, if the non NULL value is somewhere in the middle, then all will immediately return False and you don't have to check the entire list. 在这里,如果非NULL值在中间,那么all都会立即返回False而您不必检查整个列表。 Similarly, any can be used with not like this 同样, any可以被用来not喜欢这

>>> not any(item != "NULL" for item in ["NULL", "NULL", 1])
False
>>> not any(item != "NULL" for item in ["NULL", "NULL"])
True

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查列表中的所有元素是否相同? - How do I check if all elements in a list are the same? 如何检查列表B中所有列表元素在列表A中出现的频率? - How can I check how often all list elements from a list B occur in a list A? 如何获取元素列表的所有不相交子集,如果将其连接在一起,则与 python 中的初始列表相同? - How can I get all the disjoint subsets of a list of elements, and if join together it is same as the initial list in python? 检查列表的所有元素是否属于同一类型 - Check if all elements of a list are of the same type 在 Python 中,如何检查一个数组是否包含另一个数组/列表的所有元素,包括重复项? - In Python, how can I check if an array contains all elements of another array/list, including duplicates? 如何检查嵌套列表树的所有元素是否相同? - How do I check if all the elements of a nested list tree are identical? 如何在python中相同的元组列表中找到所有元素? - How do i find all the elements in a list of tuples that are same in python? 如何检查 1 个列表的所有元素是否在列表 2 中的 * 相同数量 * 和任何顺序? - How to check if all elements of 1 list are in the *same quantity* and in any order, in the list2? 如何检查数字是否可以被列表中的元素之一整除(Python)? - How can I check if a number is divisible by one of the elements in a list (Python)? 如何检查列表中每n个连续元素的格式 - How can I check the format of every n consecutive elements in a list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM