如何跳转python中的列表成员?
how to jump a list member in python?
所以我正在尝试向一群人发送消息。我想知道如果 'test1'(当前列表成员)出现错误,我如何跳转到 'test2'(下一个列表成员)。
profile_id = ['test1','test2']
for ids in profile_id:
api.send_direct_message(ids,text)
for
遍历 iprofile_id。因此,变量 ids
将首先成为元素 'test 1'
,执行 for 循环内的任何操作(即,向被称为 'test 1'
的人发送消息)。然后 ids
变成 'test2'
,一条消息被发送到 'test2'
。但是你尝试发送一条消息到人员列表,而不是被选中的人 (ids
)。我假设函数 send_direct_message
不允许列表,因此您需要将第三行设置为 api.send_direct_message(ids, text)
.
为什么不使用 TRY 然后 EXCEPT 用于相关 class?
然后您可以使用 PASS 什么也不做,继续下一步。
您可以尝试为此使用 try/except
,但前提是您 raise
在 send_direct_message
中出现异常
profile_ids = ['test1','test2']
for index, profile_id in enumerate(profile_ids):
try:
api.send_direct_message(profile_id,text)
# assume that using just Exception is not a good tone, try to use specific exception you raise in the method here instead of just Exception
except Exception as exc:
if (index+1) >= len(profile_ids):
break
api.send_direct_message(profile_ids[index+1], text)
# but in such a case think of list index out of range error, that will be thrown when list will go to an end
正如 Menashe 所说,您可以使用 TRY、EXCEPT 和 PASS。
像这样:
profile_id = ['test1','test2']
for ids in profile_id:
try:
api.send_direct_message(ids,text)
except:
pass
所以我正在尝试向一群人发送消息。我想知道如果 'test1'(当前列表成员)出现错误,我如何跳转到 'test2'(下一个列表成员)。
profile_id = ['test1','test2']
for ids in profile_id:
api.send_direct_message(ids,text)
for
遍历 iprofile_id。因此,变量 ids
将首先成为元素 'test 1'
,执行 for 循环内的任何操作(即,向被称为 'test 1'
的人发送消息)。然后 ids
变成 'test2'
,一条消息被发送到 'test2'
。但是你尝试发送一条消息到人员列表,而不是被选中的人 (ids
)。我假设函数 send_direct_message
不允许列表,因此您需要将第三行设置为 api.send_direct_message(ids, text)
.
为什么不使用 TRY 然后 EXCEPT 用于相关 class?
然后您可以使用 PASS 什么也不做,继续下一步。
您可以尝试为此使用 try/except
,但前提是您 raise
在 send_direct_message
profile_ids = ['test1','test2']
for index, profile_id in enumerate(profile_ids):
try:
api.send_direct_message(profile_id,text)
# assume that using just Exception is not a good tone, try to use specific exception you raise in the method here instead of just Exception
except Exception as exc:
if (index+1) >= len(profile_ids):
break
api.send_direct_message(profile_ids[index+1], text)
# but in such a case think of list index out of range error, that will be thrown when list will go to an end
正如 Menashe 所说,您可以使用 TRY、EXCEPT 和 PASS。 像这样:
profile_id = ['test1','test2']
for ids in profile_id:
try:
api.send_direct_message(ids,text)
except:
pass