【问题标题】:why i'm not getting more than one arbitrary arguments in the following code?为什么我在以下代码中没有得到多个任意参数?
【发布时间】:2021-03-16 10:12:22
【问题描述】:

在这段代码中,我正在编写一个提供汽车信息的函数:

car_info('subaru', 'outback', color='blue', tow_package=True)

我的功能:

def car_info(manufacturer,model,**specification):
    info = {}
    info['manufacturer'] = manufacturer
    info['name'] = model
  
    for key,values in specification.items():
        info[key] = values
        return info

【问题讨论】:

    标签: python python-3.x function


    【解决方案1】:

    您的 return 语句在 for 范围内,因此它在第一次迭代中返回。 为了解决它,使其功能范围:

    def car_info(manufacturer,model, **specification):
        info = {}
        info['manufacturer'] = manufacturer
        info['name'] = model
      
        for key,values in specification.items():
            info[key] = values
        return info
    

    您也可以只更新您的信息字典:

    def car_info(manufacturer,model, **specification):
        info = {**specification}
        info['manufacturer'] = manufacturer
        info['name'] = model
        return info
    

    【讨论】:

      猜你喜欢
      • 2019-05-05
      • 1970-01-01
      • 2019-07-17
      • 1970-01-01
      • 2021-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多