如何在其他情况下提供一组值?

2024-04-26 10:52:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种更简洁的方法来编写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'])

Tags: andofthe方法功能srcurldef
2条回答

似乎你的内部函数所做的唯一的事情就是选择你的两个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)

我想,如果没有所有的字典,这就容易多了。你知道吗

如果你把下列内容摘录到另一本字典里(如果你有两个以上的词条),不是更容易吗?你知道吗

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]]},
}

相关问题 更多 >