首页 > 解决方案 > Python将整个列表作为参数传递而不对其进行迭代?

问题描述

我是 Python 和 Pandas 的新手。下面是部分代码。当下面被硬编码时,它可以正常工作并生成预期的 json 文件。但是在函数中作为参数传递时,它不会生成任何文件。没有抛出错误。即使我将 i_indexList 硬编码为 [3,5,6,18,19] 这也不起作用,这意味着即使 i_fname 和 i_code 也没有正确传递。

需要将此作为函数,因为需要创建多个 json 文件,其名称和内容将根据用户输入而变化。因此它不能被硬编码。

请帮助以下:

  1. 当输出是 .json 文件时,下面标记的 X 行中要提到的返回值应该是什么。
  2. 作为参数传递的 List 的语法是否有任何问题。(Y 线和 Z 线)
  3. 这是由于压痕缺失吗?
def json_file(i_fname, i_indexList, i_code):

    PathLink = os.path.join(path, i_fname + '.json') #Path Name Formation = os.path.join(path, 'test' + '.json') =C:/.../test.json     
    excel_data_df = pandas.read_excel('input.xlsx',
                                          sheet_name='input_sheet1',
                                          usecols=i_indexList , #starts from 0 ,i_indexList= [3,5,6,18,19]                                   
                                          dtype={'codenum': str})  # datatype is string for codenum column
    df_filtered = excel_data_df.loc[excel_data_df["codenum"]==i_code]    # Row Filtering = ["codenum"]=='AB123'
    print(df_filtered)         
    df_filtered.columns = ['Code', 'Student Name', 'Class', 'School Name','City Name'] #renaming 
    cols_to_keep = ['Student Name', 'Class', 'School Name','City Name'] # columns to keep
    df_filtered = df_filtered[cols_to_keep]  # columns to keep
    df_filtered                                # columns to keep
    json_str = df_filtered.to_json(PathLink,orient='records',indent=2) #json converted file    
    #? return what? return json_str? -- Line X
    
#1. Mapping as per user chooses
    if Priendpoint.get() == ' Code 1':
        #Function call to create json file 
        indexList=[3,5,6,18,19] --Line Y
        json_file('test', *indexList, 'codenum') --Line Z

标签: pythonpandas

解决方案


推荐阅读