【问题标题】:Python 3: Check if a List contains an object with specific string value [duplicate]Python 3:检查列表是否包含具有特定字符串值的对象[重复]
【发布时间】:2018-11-30 23:44:07
【问题描述】:

我得到了这个字符串列表:

json = ['red', 'blue', 'green']

还有这个不变的颜色列表:

MY_COLORS = [Color('blue', 'www.example.com'), Color('red', 'www.example2.com')]

class Color:
    def __init__(self, name: str, url: str):
        self.name = name
        self.url = url

现在我想检查我的常量列表中是否有任何对象的名称值与我的字符串列表中的任何字符串匹配。 如果是这样,我想将所有匹配的对象作为列表返回以获得此结果:

some_magic(MY_COLORS, json) == [objectred, objectblue]
# no object with name green as its not inside my "MY_COLORS" constant

我尝试了Check if List of Objects contain an object with a certain attribute value 中建议的“任何”,但这并没有解决返回所有匹配对象列表的问题。

【问题讨论】:

    标签: python arrays python-3.x python-2.7


    【解决方案1】:

    你可以这样做:

    class Color:
        def __init__(self, name: str, url: str):
            self.name = name
            self.url = url
    
    MY_COLORS = [Color('blue', 'www.example.com'), Color('red', 'www.example2.com')]
    
    json = ['red', 'blue', 'green']
    set_json = set(json)
    
    result = [color for color in  MY_COLORS if color.name in set_json]
    print(result)
    

    【讨论】:

      【解决方案2】:

      len([color for color in MY_COLORS if color.name in json]) == 0 如果颜色名称与 json 变量中列出的颜色之一匹配,则返回 True,否则返回 False

      【讨论】:

        猜你喜欢
        • 2019-08-15
        • 2018-03-12
        • 1970-01-01
        • 2019-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多