【问题标题】:Check if class property value exists in list of objects [duplicate]检查对象列表中是否存在类属性值[重复]
【发布时间】:2019-10-07 12:58:04
【问题描述】:

我有一个有 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")

但这不起作用。

【问题讨论】:

  • 从一个更简单的问题开始:如何检查某个 single ButtonPress 对象 b 的时间是否为 "25"
  • 你有很多 ButtonPress 事件吗?这样的事件可以一次发生两次吗?

标签: python class attributes any


【解决方案1】:

使用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):

【讨论】:

    猜你喜欢
    • 2019-03-15
    • 2018-01-01
    • 2013-11-28
    • 2020-05-08
    • 2013-01-03
    • 2013-12-26
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多