我有一个 Python 列表,我想检查是否有任何元素为负数。是否有一个简单的函数或语法可以用来对所有元素应用“是否为负”检查,并查看其中是否有任何元素为负?我浏览了文档 http://docs.python.org/library/stdtypes.html#typesseq-mutable并且找不到类似的东西。我能想到的最好的办法是:
if (True in [t < 0 for t in x]):
# do something
我觉得这很不优雅。在 Python 中是否有更好的方法来做到这一点?
See also How to check if all elements of a list match a condition? https://stackoverflow.com/questions/10666163/ for checking the condition for all elements. Keep in mind that "any" and "all" checks are related through De Morgan's law https://stackoverflow.com/questions/2168603/, just as "or" and "and" are related.
Existing answers here use the built-in function any
to do the iteration. See How do Python's any and all functions work? https://stackoverflow.com/questions/19389490 for an explanation of any
and its counterpart, all
.
If the condition you want to check is "is found in another container", see How to check if one of the following items is in a list? https://stackoverflow.com/questions/740287 and its counterpart, How to check if all of the following items are in a list? https://stackoverflow.com/questions/3931541/. Using any
and all
will work, but more efficient solutions are possible.