pythonic替代if / else语句 [英] Pythonic alternatives to if/else statements

查看:665
本文介绍了pythonic替代if / else语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图避免一个复杂的if / elif / else语句网页。



我可以用什么pythonic方法来完成我的目标。

这是我想要实现的:



我的脚本会收到一堆不同的URL,



youtube.com,hulu.com,netflix.com,instagram.com,imgur.com等等可能有1000多个不同的域名。



我将会为每个不同的站点调用不同的指令的功能/集合。



so ....

 如果urlParsed.netloc ==www.youtube.com:
youtube()
如果urlParsed.netloc ==hulu.com :
hulu()
等于100行...



有没有办法避免这个行动方法...如果xyz网站做funcA,如果xyz网站做funcB。



我想使用这个作为一个真实的世界课程,以学习一些先进的结构化我的python代码。
所以请随便指导我对Python或基本编程的一些基本的东西。

解决方案

使用调度字典映射域功能:

  def default_handler(parsed_url):
pass

def youtube_handler (parsed_url):
pass

def hulu_handler(parsed_url):
pass

handlers = {
'www.youtube.com' :youtube_handler,
'hulu.com':hulu_handler,
}

handler = handlers.get(urlParsed.netloc,default_handler)
处理程序(urlParsed)

Python函数是一流的对象,可以像任何其他对象一样存储在字典中。 / p>

I'm trying to avoid a complex web of if/elif/else statements.

What pythonic approaches can I use to accomplish my goal.

Here's what I want to achieve:

My script will receive a slew of different urls,

youtube.com, hulu.com, netflix.com, instagram.com, imgur.com, etc, etc possibly 1000s of different domains.

I will have a function/set of different instructions that will be called for each distinct site.

so....

    if urlParsed.netloc == "www.youtube.com":
        youtube()
    if urlParsed.netloc == "hulu.com":
        hulu()
    and so on for 100s of lines....

Is there anyway to avoid this course of action...if xyz site do funcA, if xyz site do funcB.

I want to use this as a real world lesson to learn some advance structuring of my python code. So please feel free to guide me towards something fundamental to Python or programming in general.

解决方案

Use a dispatch dictionary mapping domain to function:

def default_handler(parsed_url):
    pass

def youtube_handler(parsed_url):
    pass

def hulu_handler(parsed_url):
    pass

handlers = {
    'www.youtube.com': youtube_handler,
    'hulu.com':        hulu_handler,
}

handler = handlers.get(urlParsed.netloc, default_handler)
handler(urlParsed)

Python functions are first-class objects and can be stored as values in a dictionary just like any other object.

这篇关于pythonic替代if / else语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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