问题:检查对象列表是否包含具有特定属性值的对象

我想检查对象列表是否包含具有特定属性值的对象。

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?


回答 0

文档中您可以很容易地看到,一旦找到匹配项,该any()函数True就会使返回短路。

any(x.name == "t2" for x in l)

As you can easily see from the documentation, the any() function short-circuits an returns True as soon as a match has been found.

any(x.name == "t2" for x in l)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。