如何有选择地追加列表?

2024-05-29 02:52:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我通过RFID阅读器接收信息。我要做的是删除重复项,并且只在以下两个条件下附加到列表:

  1. 如果它们的ID(epc在本例中)是唯一的并且,(完成)
  2. datetime在间隔5分钟之后(因此我可以跟踪RFID阅读器每5分钟仍在读取的相同标签)

    import paho.mqtt.client as mqtt
    import json
    
    testlist = []       
    
    def on_message(client, userdata, msg):
        payloadjson = json.loads(msg.payload.decode('utf-8'))
        line = payloadjson["value"].split(',')
        epc =  line[1]
        datetime = payloadjson['datetime']
        # datetime is in this string format '2016-04-06 03:21:17'
    
        payload = {'datetime': datetime, 'epc': epc[11:35]}
    
        # this if-statement satisfy condition 1
        if payload not in testlist:
            testlist.append(payload)
            for each in teslist:
                print (each)
    
    test = mqtt.Client(protocol = mqtt.MQTTv31)
    test.connect(host=_host, port=1883, keepalive=60, bind_address="")
    test.on_connect = on_connect
    test.on_message = on_message
    test.loop_forever() 
    

如何达到条件2?你知道吗

更新
我为我试图达到的不明确的目标道歉

我期望的输出如下所示:

{'datetime': 2016-04-06 03:21:17', 'epc': 00000001} # from Tag A
{'datetime': 2016-04-06 03:21:18', 'epc': 00000002} # from Tag B
...
...
# 5 minutes later
{'datetime': 2016-04-06 03:21:17', 'epc': 00000001} # from Tag A
{'datetime': 2016-04-06 03:21:18', 'epc': 00000002} # from Tag B
{'datetime': 2016-04-06 03:26:17', 'epc': 00000001} # from Tag A
{'datetime': 2016-04-06 03:26:18', 'epc': 00000002} # from Tag B
...
...
# Another 5 minutes later
{'datetime': 2016-04-06 03:21:17', 'epc': 00000001} # from Tag A
{'datetime': 2016-04-06 03:21:18', 'epc': 00000002} # from Tag B
{'datetime': 2016-04-06 03:26:17', 'epc': 00000001} # from Tag A
{'datetime': 2016-04-06 03:26:18', 'epc': 00000002} # from Tag B
{'datetime': 2016-04-06 03:31:17', 'epc': 00000001} # from Tag A
{'datetime': 2016-04-06 03:31:18', 'epc': 00000002} # from Tag B
...
...

Tags: infromtestmessagedatetimeontagconnect
3条回答

这可能是一种更简单的方法:

class EPC(object):
    def __init__(self, epc, date):
        self.epc = epc
        self.datetime = date
    def __eq__(self, other):
        difference = datetime.strptime(self.datetime, '%Y-%m-%d %H:%M:%S') - datetime.strptime(other.datetime, '%Y-%m-%d %H:%M:%S')
        return self.epc == other.epc and timedelta(minutes=-5) < difference < timedelta(minutes=5)
    def __ne__(self, other):
        difference = datetime.strptime(self.datetime, '%Y-%m-%d %H:%M:%S') - datetime.strptime(other.datetime, '%Y-%m-%d %H:%M:%S')
        return self.epc != other.epc or (self.epc == other.epc and (difference > timedelta(minutes=5) or difference < timedelta(minutes=-5))) 

payload = EPC(date, epc[11:35])
if payload not in test_list:
    test_list.append(payload)

我想知道epc值是否可以前后交替。也就是说,是否有可能出现epc值“A”,然后出现epc值“B”,然后再次出现epc值“A”?(或者可能是A、B、C等?)你知道吗

如果假设只有一个标记,那么只需查看最近的条目:

last_tag = testlist[-1]
last_dt = last_tag['datetime']

现在,您可以将当前值datetime与上一个值进行比较,看看它是否适合您的窗口。你知道吗

不过,请注意,将datetime代码放在has中实际上对现有代码不起作用,因为datetime一直在更改,因此payload not in testlist将始终为真,除非您在同一秒获得两个RFID读取。你知道吗

你的问题有点不清楚。假设您想要更新testlist,如果它是一个新的epc,或者从上次更新到epc已经超过了5分钟。在这种情况下,dict()可以很好地工作。使用标准库中的datetime模块计算日期或时间的差异。你知道吗

import paho.mqtt.client as mqtt
import json
import datetime as dt

TIMELIMIT = dt.timedelta(minutes=5)

testlist = {}       ## <<-- changed this to a dict()

def on_message(client, userdata, msg):
    payloadjson = json.loads(msg.payload.decode('utf-8'))
    line = payloadjson["value"].split(',')
    epc =  line[1]

    # this converts the time stamp string to something python can
    # use in date / time calculations
    when = dt.datetime.strptime(payloadjson['datetime'], '%Y-%m-%d %H:%M:%S')

    if epc not in testlist or when - testlist[epc] > TIMELIMIT:
        testlist[epc] = when

        for epc, when in teslist.items():
            print (epc, when)

相关问题 更多 >

    热门问题