相当于LINQ的Python所有功能? [英] Python equivalent of LINQ All function?

查看:112
本文介绍了相当于LINQ的Python所有功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

测试集合中所有元素是否都满足条件的惯用Python方法是什么? ( .NET All()方法在C#中很好地填补了这一空白.)

What is the idiomatic Python way to test if all elements in a collection satisfy a condition? (The .NET All() method fills this niche nicely in C#.)

有一个明显的循环方法:

There's the obvious loop method:

all_match = True
for x in stuff:
    if not test(x):
        all_match = False
        break

列表理解可以解决问题,但似乎很浪费:

And a list comprehension could do the trick, but seems wasteful:

all_match = len([ False for x in stuff if not test(x) ]) > 0

肯定会有一些更优雅的东西……我想念什么?

There's got to be something more elegant... What am I missing?

推荐答案

all_match = all(test(x) for x in stuff)

这是一种短路,不需要任何东西列出来-任何可迭代的方法都可以工作-因此具有几个不错的功能.

This short-circuits and doesn't require stuff to be a list -- anything iterable will work -- so has several nice features.

也有类似的

any_match = any(test(x) for x in stuff)

这篇关于相当于LINQ的Python所有功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆