检查对象列表中是否存在类属性值

时间:2019-10-07 12:58:04

标签: python class attributes any

我有一个具有2个属性的类:

class ButtonPress():
    def __init__(self, time, button):
        self.time = time
        self.button = button

我创建了一个列表,其中包含ButtonPress个对象:

buttonlist = []
buttonlist.append(ButtonPress("25", "a")
buttonlist.append(ButtonPress("5", "b"))

如何检查列表中是否有任何对象具有特定的time值?我正在尝试:

if "25" in buttonlist[:]['time']
    print("yaaay")
else:
    print("feck")

但这不起作用。

1 个答案:

答案 0 :(得分:4)

使用any

class ButtonPress():
    def __init__(self, time, button):
        self.time = time
        self.button = button

buttonlist = []
buttonlist.append(ButtonPress("25", "a"))
buttonlist.append(ButtonPress("5", "b"))

if any(button.time == "25" for button in buttonlist):
    print("yaaay")
else:
    print("feck")

输出

yaaay

使用in的替代方法如下:

if "25" in (button.time for button in buttonlist):