简体   繁体   English

在Python中拒绝列表的快速方法

[英]Quick way to reject a list in Python

I have a list of items in python, and a way to check if the item is valid or not. 我有一个python中的项目列表,以及一种检查项目是否有效的方法。 I need to reject the entire list if any one of items there is invalid. 如果任何一个项目无效,我需要拒绝整个列表。 I could do this: 我能做到这一点:

def valid(myList):
    for x in myList:
        if isInvalid(x):
           return False
    return True

Is there a more Pythonic way for doing this? 有更多的Pythonic方式吗? You could filter it, but that would evaluate all the items in the list, when evaluating just the first one could be sufficient (if it is bad)... 你可以过滤它,但是这将评估列表中的所有项目,当评估第一个项目就足够了(如果它是坏的)......

Thank you very much for your help. 非常感谢您的帮助。

The typical way to do this is to use the builtin any function with a generator expression 执行此操作的典型方法是使用内置any具有生成器表达式的函数

if any(isInvalid(x) for x in myList):
   #reject

The syntax is clean and elegant and you get the same short-circuiting behavior that you had on your original function. 语法干净而优雅,您可以获得与原始函数相同的短路行为。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM