试图围绕 python 函数中的可变输入参数

Trying to wrap my head around variable input arguments in python functions

所以首先我会说这是我正在处理的代码挑战,其参数如下。

So, first, write a function named covers that accepts a single parameter, a set of topics. Have the function return a list of courses from COURSES where the supplied set and the course's value (also a set) overlap. For example, covers({"Python"}) would return ["Python Basics"].

这是我从中提取的字典,其中包含课程主题的嵌套集。

COURSES = {
"Python Basics": {"Python", "functions", "variables",
                  "booleans", "integers", "floats",
                  "arrays", "strings", "exceptions",
                  "conditions", "input", "loops"},
"Java Basics": {"Java", "strings", "variables",
                "input", "exceptions", "integers",
                "booleans", "loops"},
"PHP Basics": {"PHP", "variables", "conditions",
               "integers", "floats", "strings",
               "booleans", "HTML"},
"Ruby Basics": {"Ruby", "strings", "floats",
                "integers", "conditions",
                "functions", "input"}}

现在,搜索 dict 的集合是 for 循环的一种非常简单的前向使用,但挑战听起来像是要我创建一组新的课程名称,其主题与参数输入相匹配,并且将结果输出为列表。

def covers(topics):
    hold_set = set()
    for key in COURSES.keys():
        if topics in COURSES[key]:
            result = key
            hold_set.add(result)
        else:
            continue
    conversion = list(hold_set)
    return conversion

现在我的第一个问题是接受可变数量的参数,我对 *args / **kwargs 不是很熟悉,所以我在这里尝试使用它们大多只是导致打印函数给我空列表.另一个是创建一个额外的不必要的集合来与在 dict 中搜索子集后创建的新集合进行比较,这似乎是多余的,因为 hold_set 已经包含名称并将它们与我假设的 .intersection 进行比较() 在将结果转换为列表之前,只需做更多的工作就可以获得相同的结果。

但我离题了,现在我假设这里的主要问题是函数无法接受关于主题搜索参数的可变数量的参数(因为提交挑战时,它说 "Didn't get the right output from covers."),因此,如果有人能阐明我是如何做到这一点的,那么我将不胜感激,因为几天后我的大脑开始变得混乱,我已经开始阅读有关计算机科学其他领域的书籍来减压。

如果你想使用多个参数,你可以试试这个:

def covers(*args):

    mydict = dict()

    for arg in args:
        mylist = list()

        for k, v in COURSES.items():
            if arg in v:
                mylist.append(k)

        mydict[arg] = mylist

    return mydict

使用 dict 和列表理解,你可以缩短它:

def covers(*args):
    return {arg: [k for k, v in COURSES.items() if arg in v] for arg in args}

这会生成一个字典,其中包含您提供的每个字符串的条目。条目的值是包含所有匹配课程的列表。所以如果你这样称呼它:

covers('variables', 'Python')

你得到以下命令:

{'variables': ['PHP Basics', 'Java Basics', 'Python Basics'], 'Python': ['Python Basics']}

关于多个参数的问题:*args 捕获列表中所有未在函数定义中显式声明的位置参数,**kwargs 类似地捕获字典中的所有关键字参数。因此,通过仅将 *args 定义为函数参数,函数调用的所有参数都存储为列表,可以照常迭代。