代码之家  ›  专栏  ›  技术社区  ›  GregH

根据python中的对象键从列表中检索对象的元素

  •  1
  • GregH  · 技术社区  · 6 年前

    只是想知道是否有一种更优雅的方法根据对象是否包含特定的值从列表中的特定对象中检索值,或者我是否需要编写一些东西来遍历列表并查看每个对象。例如:

    class C(object):
        def __init__(self, url, value):
            self.url=url
            self.value=value
    
    obj1 = C("http://1", 1)
    obj2 = C("http://2", 2)
    mylist = [obj1, obj2]
    
    # I want to search  mylist and retrieve the "value" element if there is
    # an object with a "url" value of "http://2"...basically retrieve the 
    # value 2 if an element exists in the list with a url value of "http://2"
    

    当然,如果我知道它存在于列表的第一个元素中,我可以通过以下方式检索它:

    mylist[1].value
    

    但是,在我的例子中,我不知道该对象是否存在于列表中,也不知道它存在于列表中的哪个位置。

    1 回复  |  直到 6 年前
        1
  •  1
  •   jpp    6 年前

    您需要遍历列表并查看每个对象。

    如果你期望一场比赛,你可以使用 next 使用生成器表达式:

    res = next((i.value for i in mylist if i.url == 'http://2'), None)
    
    print(res)
    # 2
    

    如果需要多个匹配项,可以使用列表理解:

    res = [i.value for i in mylist if i.url == 'http://2']
    
    print(res)
    # [2]