Python 避免冗长的elif列表,使if循环更加高效和动态

Python 避免冗长的elif列表,使if循环更加高效和动态,python,for-loop,Python,For Loop,我想检查id compare it IDList,如果它们相同,它应该写 有更好的解决办法吗? 注意:chatid是实时抓取的 api=[1232312,123123,1231231] IDList=[-100123123,100123123,100123123] try: if chatid==IDList[0]: my_event_handler.id=api[0] print("hook1") elif chatid==

我想检查id compare it IDList,如果它们相同,它应该写 有更好的解决办法吗? 注意:chatid是实时抓取的

api=[1232312,123123,1231231]
IDList=[-100123123,100123123,100123123]

try:
    if chatid==IDList[0]:
        my_event_handler.id=api[0]
        print("hook1")
    elif chatid==IDList[1]:
        my_event_handler.api=api[1]
        print("hook2")
    elif chatid==IDList[2]:
        my_event_handler.id=api[2]
        print("hook3")
    elif chatid==IDList[3]:
        my_event_handler.id=api[3]
        print("hook4")
    elif chatid==IDList[4]:
        my_event_handler.id=api[4]
        print("hook5")
这很有效


我想做的是在范围内为x做一个for循环
(数量):
以获得完美的钩子数。但是我该怎么做呢?

如果索引总是那样规则,你可以这样做:

枚举(IDList)中i,id的

如果chatid==id\ux:
my_event_handler.id=api[i]
打印(f“hook{i+1}”)
中断#如果您只需要找到第一个匹配项,请在此处退出循环
试试这个:

 for i in range(len(IDList)):
    if chatid == IDList[i]:
        my_event_handler.id=api[i]
        print("hook" + str(i+1))
        break # You got the answer, exit the loop 

如果
api
IDList
始终具有相同数量的元素,则可以使用来同时迭代这两个列表,并避免使用基于索引的查找

只添加一个计数器,以便从1开始打印“钩子”。如果不需要,请将其移除

对于枚举(zip(api,IDList),start=1)中的idx(api_num,ID):
如果chatid==ID:
my_event_handler.id=api_num
打印(f'hook{idx}')
break#找到后退出,对“else”很重要`
其他:
# !!! `else`for`,而不是`if``
#如果循环未中断或列表为空,则执行将到达此处
#根据需要处理。这里举一个错误为例
raise VALUERROR(未找到f'chatid:{chatid}')
#或者为其指定一个默认api和挂钩