简体   繁体   English

python,将if / elif替换为字典

[英]python, replace if/elif with dictionary

Folks, How would you rewrite the if/elif in the 'checkme' function with a dictionary? 伙计们,你如何用字典重写'checkme'函数中的if / elif?

def dosomething(queue):
    ...

def checkme(queue):
  """ Consume Message """
  if queue == 'foo':
    username = 'foo'
    password = 'vlTTdhML'
  elif queue == 'bar':
    username = 'bar'
    password = 'xneoYb2c'
  elif queue == 'baz':
    username = 'baz'
    password = 'wnkyVsBI'
  ...
  dosomething(queue)

def main():
    checkme('foo')
    checkme('bar')
    checkme('baz')

You could do something like this: 你可以这样做:

CHECK_ME = {'foo': 'vlTTdhML', 'bar': 'xneoYb2c', 'baz': 'wnkyVsBI'}

def checkme(queue):
    username, password = queue, CHECK_ME.get(queue)
    #May be some more check here, like
    if not password:
        print 'password is none'
        #Or do something more relevant here

    #rest of the code. 

It looks like you're relying on side-effects, especially with the dosomething(queue) part, so I'll assume that is all handled OK in my solution, but I'd prefer to do it in a way that did not rely on side-effects. 看起来你依赖于副作用,尤其是dosomething(queue)部分,所以我认为在我的解决方案中处理完全正常,但我更愿意以不依赖的方式进行处理副作用。

def checkme(queue):

    class to_do_dict(dict):
        def __missing__(self, itm):
            dosomething(itm)

    to_do = to_do_dict({
        "foo":("foo", "v1TTdhML"),
        "bar":("bar", "xneoYb2c")})

    username, password = to_do[queue]

Try this: 尝试这个:

passwords = {'foo':'vlTTdhML', 'bar':'xneoYb2c', 'baz':'wnkyVsBI'}
username, password = queue, passwords[queue]

The above assumes that there's a password in the dictionary for every user. 以上假设字典中的每个用户都有一个密码。 If that's not the case, better play it safe and use this: 如果不是这样,最好安全地使用它:

username, password = queue, passwords.get(queue, None)

Either way, you can simply call dosomething(queue) at the end. 无论哪种方式,您都可以在最后调用dosomething(queue) As currently stated in the question, dosomething is always invoked. 正如目前在问题中所述,总是会调用dosomething

You can do this: 你可以这样做:

{'foo': {'username': 'foo', 'password': 'vlTTdhML'}} {'foo':{'username':'foo','password':'vlTTdhML'}}

And just keep adding dictionaries as you'd like. 只需按照您的意愿添加词典。

Nested dictionaries would do the trick. 嵌套字典可以解决这个问题。

To set the usernames and passwords: 设置用户名和密码:

queue = {}

queue["foo"] = {"username": "foo", "password": "vlTTdhML" }
queue["bar"] = {"username": "bar", "password": "xneoYb2c" }

And to check whether the username/password exists: 并检查用户名/密码是否存在:

if queue.get("foo"):
 username = queue["foo"]["username"]
 password = queue["foo"]["password"]

else:
 # username does not exist, so do something
 print "username does not exist"

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

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