如何在两种情况下提供一组值?

时间:2013-09-02 16:22:01

标签: python algorithm

我正在寻找一种更简洁的方式来编写lookup_and_url函数。我认为必须有一种更简洁的方式来声明和实现我的逻辑。我已尽力准确地描述代码本身的外部函数和内部函数:

def render(opener='corp'):
    """render will render a carousel of videos, with the opener being
    corp or uk and the follower being the other"""

    def lookup_and_url():
        """"lookup_and_url() returns the DOM id and url for the
        opening video (the opener) and the video to follow (the follower).

        It returns a dictionary that allows a loop to make a DOM
        lookup of the id of the HTML element and then replace its
        `src attribute with the provided URL
        """

        src = dict(
            corp='http://www.youtube.com/embed/0lrqEGlu0Fo',
            uk='http://www.youtube.com/embed/30MfCTLhdZ4'
        )

        if opener == 'corp':
            return dict(
                opener = dict(lookup='opener', src=src['corp']),
                follower = dict(lookup='follower', src=src['uk'])
            )
        else:
            return dict(
                opener = dict(lookup='opener', src=src['uk']),
                follower = dict(lookup='follower', src=src['corp'])
            )

    lookup_and_src = lookup_and_url()

    for replace in lookup_and_src:
        root.findmeld(lookup_and_src['lookup']).attributes(src=lookup_and_src['src'])

2 个答案:

答案 0 :(得分:3)

看起来你的内部函数唯一能做的就是选择你的两个URL中的哪一个是“开启者”,哪个是“追随者”。你为构建嵌套字典所做的所有工作都是毫无意义的。我想你可以让这个变得更加简单:

def render(opener='corp'):
    corp = 'http://www.youtube.com/embed/0lrqEGlu0Fo',
    uk = 'http://www.youtube.com/embed/30MfCTLhdZ4'

    o, f = (corp, uk) if opener == "corp" else (uk, corp)

    root.findmeld('opener').attributes(src=o)
    root.findmeld('follower').attributes(src=f)

我认为,如果没有所有词典,这会更容易理解。

答案 1 :(得分:1)

如果将以下内容提取到另一个词典中(如果您有两个以上的词条)会不会更容易?

src = {
    'corp': 'http://www.youtube.com/embed/0lrqEGlu0Fo',
    'uk': 'http://www.youtube.com/embed/30MfCTLhdZ4',
}

followers = {
    'corp': 'uk', 
    'uk': 'corp',
}

return {
    'opener': {'lookup': 'opener', 'src': src[opener]},
    'follower': {'lookup': 'follower', 'src': src[followers[opener]]},
}