首页 > 解决方案 > Python for-loop in range not providing desired result

问题描述

I have the following python for-loop which is supposed to loop round RANGE numbers of time. I specify RANGE at the start of the code, so for example, imagine the range is 5.

There is then a uuid_list containing 2 uuids. There should be a message created for each.

for i in range(RANGE):
                data = MESSAGE[i]
                message = data
                mqtt_connection.publish(topic=TOPIC, payload=json.dumps(message), 
                qos=mqtt.QoS.AT_LEAST_ONCE)
                print("Published: '" + json.dumps(message) + "' to the topic: " + TOPIC)
                t.sleep(20)

Since I have specified the RANGE as 5, I am expecting a result of 5 generated messages for EACH uuid. However, with the above code, I am only getting 5 messages for the first uuid.

To try and rectify this I have also tried ...

for i in range(RANGE):
                data = MESSAGE[i+1]
                message = data
                mqtt_connection.publish(topic=TOPIC, payload=json.dumps(message), 
                qos=mqtt.QoS.AT_LEAST_ONCE)
                print("Published: '" + json.dumps(message) + "' to the topic: " + TOPIC)
                t.sleep(20)

The RANGE is still 5. But now I am getting 8 messages for the first uuid and 2 for the second uuid.

Can anyone please advise how my line data = MESSAGE[i] should be specified in order to achieve the desired RANGE for each uuid?

标签: pythonpython-3.xloopsfor-loop

解决方案


When you do for i in range(RANGE), i value ranges from 0 to 4 and that will access only the first 5 elements of MESSAGE

For RANGE = 5 and two uuids MESSAGE has 5 * 2 = 10 elements. To fetch all ten messages, you can either do

for i in range(RANGE * len(uuid_list):
    message = MESSAGE[i]
    # rest of the code

OR

for message in MESSAGE:
    # rest of the code

推荐阅读