在Python中使用循环和数组来改变条件 [英] Change conditions using loop and array in python

查看:212
本文介绍了在Python中使用循环和数组来改变条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中有旧的脚本,在哪里



pre $如果__name__ =='__main__':< BR>

我们调用函数的参数。如果它的参数等于一些字符串,我们应该调用函数。
旧代码。

  if sys.argv [1] =='add':
sys.exit(add(db,usr ))
if sys.argv [1] =='rem':
sys.exit(rem(db,usr))
if sys.argv [1] =='rmusr' :
sys.exit(rmusr(db,usr))

第一次,我想过切换案例,但我怎么知道,蟒蛇没有它。我试图循环和数组。
我可以使用它吗?对不起,我开始学习Python,2小时前。但是,这是非常有趣的,我希望你能帮助我。

  actions = ['add','rem' ,'rmusr'] 
for a actions:
if sys.argv [1] =='a':
sys.exit(a(db,usr))

是否正确?我怎么知道,我们不应该用$来调用变量。请帮忙。

解决方案

您可以将函数添加到字典中,然后使用用户输入字符串来检索函数:



$ $ $ $ $ $ $ $ $'$'$'$'$''$'$' :rmusr,
}

action = sys.argv [1]

如果在动作中执行动作:
sys.exit(actions [action]( db,usr))


i have and old script in python, where in

if __name__ == '__main__': <br>

We call arguments of functions. And if it argument equals some string we should call function. Old code.

if sys.argv[1] == 'add':
    sys.exit(add(db, usr))
if sys.argv[1] == 'rem':
    sys.exit(rem(db, usr))
if sys.argv[1] == 'rmusr':
    sys.exit(rmusr(db, usr))

At the first time, i thought about "switch case", but how i find out, python does not have it. And i tried to loop and array. Can i use it on this ? Sorry, i started learn python, 2 hours ago. But it is very interesting, and i hope, that you can help me.

 actions = ['add','rem','rmusr']
    for a in actions:
    if sys.argv[1] == 'a':
        sys.exit(a(db, usr))

Is it correct ? How i find out, we should not call variables with "$". Please help.

解决方案

You can add the functions to the dictionary and then use the user-input string to retrieve the function:

actions = {
    'add': add,
    'rem': rem,
    'rmusr': rmusr,
}

action = sys.argv[1]

if action in actions:
    sys.exit(actions[action](db, usr))

这篇关于在Python中使用循环和数组来改变条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆