检查对象列表是否包含具有特定属性值的对象
我想检查我的对象列表是否包含具有特定属性值的对象。
class Test:
def __init__(self, name):
self.name = name
# in main()
l = []
l.append(Test("t1"))
l.append(Test("t2"))
l.append(Test("t2"))
我想要一种方法来检查列表是否包含名称为 "t1"
的对象。怎么办呢?我发现https://stackoverflow.com/a/598415/292291,
[x for x in myList if x.n == 30] # list of all matches
any(x.n == 30 for x in myList) # if there is any matches
[i for i,x in enumerate(myList) if x.n == 30] # indices of all matches
def first(iterable, default=None):
for item in iterable:
return item
return default
first(x for x in myList if x.n == 30) # the first match, if any
我不想经历整个过程每次都列出来;我只需要知道是否有 1 个匹配的实例。 first(...)
或 any(...)
或其他东西会这样做吗?
I want to check if my list of objects contain an object with a certain attribute value.
class Test:
def __init__(self, name):
self.name = name
# in main()
l = []
l.append(Test("t1"))
l.append(Test("t2"))
l.append(Test("t2"))
I want a way of checking if list contains an object with name "t1"
for example. How can it be done? I found https://stackoverflow.com/a/598415/292291,
[x for x in myList if x.n == 30] # list of all matches
any(x.n == 30 for x in myList) # if there is any matches
[i for i,x in enumerate(myList) if x.n == 30] # indices of all matches
def first(iterable, default=None):
for item in iterable:
return item
return default
first(x for x in myList if x.n == 30) # the first match, if any
I don't want to go through the whole list every time; I just need to know if there's 1 instance which matches. Will first(...)
or any(...)
or something else do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如您可以从文档中轻松看到,
any()<一旦找到匹配项,/code> 函数就会短路并返回
True
。As you can easily see from the documentation, the
any()
function short-circuits an returnsTrue
as soon as a match has been found.另一个内置函数
next()
可用于此工作。它在条件为 True 的第一个实例处停止,与any()
非常相似。此外,
next()
可以在条件为True
的情况下返回对象本身(因此其行为类似于 OP 中的first()
函数)。Another built-in function
next()
can be used for this job. It stops at the first instance where the condition isTrue
much likeany()
.Also,
next()
can return the object itself where the condition isTrue
(so behaves likefirst()
function in the OP).扩展这里已经给出的非常出色的答案,我编写了一个 lambda:
我们可以通过以下方式使用它:
Extending the very excellent answer given here already, I wrote a lambda:
which we can use in these ways: