[英]Python list of objects query
I have a python class here:我在这里有一个 python class :
class device:
def __init__(self, hostname, ipaddress, status, version, sensor_id, first_seen) -> None:
self.hostname = hostname
self.ipaddress = ipaddress
self.status = status
self.version = version
self.sensor_id = sensor_id
self.first_seen = first_seen
Lets say I have 3 instances of this which are all identical except the sensor_id and first_seen, these objects are stored in a list假设我有 3 个实例,除了 sensor_id 和 first_seen 之外,它们都是相同的,这些对象存储在一个列表中
sensor_list = []
dev1 = device("PC1", "1.1.1.1", "offline", "21.1", "ID_0001", "09/08/2022")
dev2 = device("PC1", "1.1.1.1", "offline", "21.1", "ID_0002", "09/09/2022")
dev3 = device("PC1", "1.1.1.1", "offline", "21.1", "ID_0003", "14/08/2022")
sensor_list.append(dev1)
sensor_list.append(dev2)
sensor_list.append(dev3)
How could I search the list of objects, and retrieve the sensor_id with the latest first_seen timestamp?如何搜索对象列表,并使用最新的 first_seen 时间戳检索 sensor_id? Is it possible to do this using some kind of list comprehension or is it a little more complicated than that?
是否可以使用某种列表理解来做到这一点,还是比这更复杂一些?
latest = [x for x in sensor_list ???]
Use max()
使用
max()
latest = max(sensorlist, key = lambda s: datetime.strptime(s.first_seen, '%d/%m/%Y'))
It would be simpler if you converted first_seen
to a datetime
when you create the object rather than having to do it whenever you access the object.如果在创建 object 时将
first_seen
转换为datetime
时间,而不是每次访问 object 时都必须这样做,这会更简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.