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