python - 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?
解决方案
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
推荐阅读
- reactjs - 映射数组中的项目 - 反应
- prolog - 编写一个适用于循环图的谓词,以使用 prolog 检查两个节点之间是否存在路径
- c++ - 标准::原子
ARM(树莓派 3)上的无锁不一致 - typescript - Typescript 中枚举的多个键声明
- quire-api - “导出项目” Quire API 文档
- git - 使用 Hugo 框架为不同的分支部署 GitLab 页面?
- python - 如何修复不和谐机器人中的“事件循环已关闭”
- python - Groupby 和过滤数据集
- django - Django ManytoManyfields错误`AttributeError:'ManyRelatedManager'对象没有属性'dev_id'`
- typescript - TypeError:无法读取未定义的属性“符号”[JWT / Nestjs / e2e 测试]