我有一个具有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")
但这不起作用。
答案 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):