【问题标题】:Function parameters to python dictionarypython字典的函数参数
【发布时间】:2017-02-17 17:10:45
【问题描述】:

我正在编写一个执行其他几个函数的包装函数。

为了简化这个问题,假设只有包装函数和函数 calc_days 返回开始日期和结束日期之间的天数。您还可以将日期列表传递给开始日期和结束日期参数,此时函数返回开始日期和结束日期的每个可能组合的天数。

def wrapper(startd,endd):
   return calc_days(startd,endd)

现在我想让函数的用户可以通过编辑一个类似这样的 csv 文件来提供输入参数:

startd;01/01/1900
startd;01/01/1950  
endd;01/01/2000

所以包装器会变成这样(使用 pandas 读取 csv):

def wrapper(csv_file, startd, endd):
  if os.path.isfile(csv_file):
    input_param = pd.read_csv(csv_file, ...)
    input_dict = {i: list(v) for i,v in input_param.groupby(0)[1]}
  else:
    input_dict = {'date1': date1, 'date2': date2}
  return calc_date(input_dict['date1'], input_dict['date2'])

我做 groupby 的东西,因为它会在我的字典中为开始日期创建一个列表:

{startdd : [01/01/1900,01/01/1950]}

现在我的问题是:在实际设置中,我没有 2 个输入参数,但我有大约 30 个输入参数。因此,它想以输入参数 (startdd) 作为键和输入参数的内容 ([01/01/1900,01/01/1950) 动态构建字典]) 作为值。

除了为每个输入参数手动创建之外,是否有安全的方法来动态构建此字典?

【问题讨论】:

  • 我不确定我是否 100% 理解但 **kwds 不符合您的要求?
  • 你的问题不是重点……说来话长

标签: python function dictionary input parameters


【解决方案1】:

是的,this StackOverflow question 提供了您需要的大部分信息。您必须遍历索引和值才能将所有内容绑定在一起。

def insertintoData(aItem, bItem, cDict):
    if not aItem in cDict:
        cDict[aItem] = [(bItem)]
    else:
        cDict[aItem].append((bItem))

input_dict = {}
for i in input_param:
    insertintoData(i[0], i[1], input_dict)

您的 groupby 将由函数中的 if/else 处理。

【讨论】:

    猜你喜欢
    • 2017-09-04
    • 2018-08-14
    • 2016-03-19
    • 1970-01-01
    • 2021-07-15
    • 2019-05-19
    • 1970-01-01
    • 2019-12-26
    相关资源
    最近更新 更多