简体   繁体   English

对于循环语句不读取if语句继续下一次迭代

[英]For loop statement not reading if statement to continue to next iteration

I have code that looks like this: 我的代码看起来像这样:

for item in items:

    if item.data["position"] == '5':
        item.delete() 
        continue
    elif item.data["lang"] == 'SPA':
        message_body = my_message_spa[item.data["position"]]
    else:
        message_body = my_message_eng[item.data["position"]] # English (default)

    message = client.messages.create(
        item.data["phone_number"],                    
        body=message_body,
        from_="xxxx"                           
    )
    # increment the position for this user
    item.data["position"]+=1

This code is meant to send messages to an user. 此代码旨在向用户发送消息。 Items is a list of dictionaries that has an user's phone number, date, language, and position. Items是包含用户电话号码,日期,语言和位置的字典列表。 Position refers to their position in the sequence of messages. 位置是指它们在消息序列中的位置。 I would like to check the position of a user and if they have already received 5 messages, then it should be removed from the list and continue on to the next user. 我想检查用户的位置,如果他们已经收到5消息,那么它应该从列表中删除并继续下一个用户。 If the position of the user is <5 then it should go into the else if statements and send messages according to the conditions met. 如果用户的位置<5那么它应该进入else if语句并根据满足的条件发送消息。

The list of dictionaries has the following structure: 词典列表具有以下结构:

{'phone_number': '+1234567890', 'position': 5, 'lang': 'ENG', 'Date': '2018-08-17 00:03:46'}
{'phone_number': '+0987654321', 'position': 2, 'lang': 'ENG', 'Date': '2018-12-18 07:10:47'}

The code worked fine previously and the new part I am adding/testing is the if statement checking for position but it seems like that if statement does not get invoked at all and goes straight to the below elif checking for 'lang' and sends the message and increments the position for the user. 代码工作正常,我添加/测试的新部分是if语句检查位置,但似乎if语句根本没有被调用,直接到下面的elif检查'lang'并发送消息并增加用户的位置。 In my case, the user's position gets incremented to 6 . 在我的情况下,用户的位置增加到6

You seem to be comparing the value incorrectly. 您似乎错误地比较了该值。 You are trying to compare a string "5" to an integer 5. 您正在尝试将字符串“5”与整数5进行比较。

if item.data["position"] == '5':

note the quotes around 5. 请注意5左右的报价。

For example: 例如:

print(1 == "1")
print(1 == 1)

returns False for the first one, and True for the second one. 第一个返回False,第二个返回True。

You also should not delete items from something like a list when iterating over it. 在迭代它时,您也不应该从列表中删除项目。 Instead try creating a copy or using list comprehension. 而是尝试创建副本或使用列表理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM