Python equivalent of Scala's exists() function?

心已入冬 提交于 2019-12-11 03:55:13

问题


Scala lists have an exists() function that returns a boolean if the list has an element that satisfies your predicate.

Is there a way to do this in python that's just as clean?

I've been using

if next(x for x in mylist if x > 10): return Something

Is there a better way?


回答1:


Use any:

if any(x > 10 for x in mylist):
    return Something

You can complement this with all, and use not any and not all to round it out.

Your way of using next will raise an exception if it doesn't find anything. You can pass it an additional default value to return, instead:

if next((x for x in mylist if x > 10), None):
    return Something


来源:https://stackoverflow.com/questions/33048555/python-equivalent-of-scalas-exists-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!