找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 56|回复: 1

[求助] 如何简化elseif语句?

1

主题

1

帖子

1

积分

贫民

积分
1
badbat 发表于 7 天前 | 显示全部楼层 |阅读模式
代码中elseif太多了,有没有什么办法简化?比如:
if chromeOpened == 0:
    chromeOpened = 1
    driver1 = openChromeX(myChromeDataList[1])
    driver2 = openChromeX(myChromeDataList[2])
    driver3 = openChromeX(myChromeDataList[3])
    whichGroup = 1
elif chromeOpened == 1:
    chromeOpened = 2
    closeChromeX(driver1)
    closeChromeX(driver2)
    closeChromeX(driver3)
    time.sleep(2)
    driver4 = openChromeX(myChromeDataList[4])
    driver5 = openChromeX(myChromeDataList[5])
    driver6 = openChromeX(myChromeDataList[6])
    whichGroup = 2
elif chromeOpened == 2:
    chromeOpened = 3
    closeChromeX(driver4)
    closeChromeX(driver5)
    closeChromeX(driver6)
    time.sleep(2)
    driver7 = openChromeX(myChromeDataList[7])
    driver8 = openChromeX(myChromeDataList[8])
    driver9 = openChromeX(myChromeDataList[9])
    whichGroup = 3
elif chromeOpened == 3:
    chromeOpened = 4
    closeChromeX(driver7)
    closeChromeX(driver8)
    closeChromeX(driver9)
    time.sleep(2)
    driver10 = openChromeX(myChromeDataList[10])
    driver11 = openChromeX(myChromeDataList[11])
    driver12 = openChromeX(myChromeDataList[12])
    whichGroup = 4
elif chromeOpened == 4:
    chromeOpened = 5
    closeChromeX(driver10)
    closeChromeX(driver11)
    closeChromeX(driver12)
    time.sleep(2)
    driver13 = openChromeX(myChromeDataList[13])
    driver14 = openChromeX(myChromeDataList[14])
    driver15 = openChromeX(myChromeDataList[15])
    whichGroup = 5
elif chromeOpened == 5:
    chromeOpened = 6
    closeChromeX(driver13)
    closeChromeX(driver14)
    closeChromeX(driver15)
    time.sleep(2)
    driver16 = openChromeX(myChromeDataList[16])
    driver17 = openChromeX(myChromeDataList[17])
    driver18 = openChromeX(myChromeDataList[18])
    whichGroup = 6
elif chromeOpened == 6:
    chromeOpened = 7
    closeChromeX(driver16)
    closeChromeX(driver17)
    closeChromeX(driver18)
    time.sleep(2)
    driver19 = openChromeX(myChromeDataList[19])
    driver20 = openChromeX(myChromeDataList[20])
    driver21 = openChromeX(myChromeDataList[21])
    whichGroup = 7
elif chromeOpened == 7:
    chromeOpened = 1
    closeChromeX(driver19)
    closeChromeX(driver20)
    closeChromeX(driver21)
    time.sleep(2)
    driver1 = openChromeX(myChromeDataList[1])
    driver2 = openChromeX(myChromeDataList[2])
    driver3 = openChromeX(myChromeDataList[3])
    whichGroup = 1
回复

使用道具 举报

0

主题

1

帖子

1

积分

贫民

积分
1
xgd6610 发表于 昨天 15:31 | 显示全部楼层
有办法,写一个专门处理的dict,伪代码如下:
def function1():
        ...
       

trans_dict = {
        1: function1,
        2: function2,
        3: function3,
        4: function4,
        5: function5,
        6: function6
}

function = trans_dict.get(chromeOpened)
function()
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表