Python 从现有列表中的元素形成新列表,并指定工作表名称

Python 从现有列表中的元素形成新列表,并指定工作表名称,python,list,dictionary,variables,Python,List,Dictionary,Variables,标题听起来可能令人困惑……但这就是我需要做的: 我有一个列表(长度可变,根据不同的场景有不同的值),例如:list1=['backup','downloadMedia','createAlbum']。从这个列表中,我需要为这些项目中的每一个创建以下内容之一:(显然,名称将根据列表中的项目进行更新) 我需要创建一个名为:testcases\u backup=[]的新列表 我需要创建一个名为:results_backup=[]的新列表 我需要创建一个新列表,名为:屏幕截图\路径\备份=[] 最后,我

标题听起来可能令人困惑……但这就是我需要做的:

我有一个列表(长度可变,根据不同的场景有不同的值),例如:list1=['backup','downloadMedia','createAlbum']。从这个列表中,我需要为这些项目中的每一个创建以下内容之一:(显然,名称将根据列表中的项目进行更新)

  • 我需要创建一个名为:testcases\u backup=[]的新列表
  • 我需要创建一个名为:results_backup=[]的新列表
  • 我需要创建一个新列表,名为:屏幕截图\路径\备份=[]
  • 最后,我需要打开一个新的工作表,它需要:worksheet1=workbook.add_worksheet('Results')。值得注意的是,在这种情况下,我需要迭代1,2,3,。。。用于列表中每个项目的工作表名称。因此,对于“备份”的第一次迭代,它将是工作表1。2个用于下载媒体等
  • 我曾尝试使用字典,但目前我没有取得任何实际进展

    我的尝试:(我对字典的经验非常有限)

    我想这可能行得通……但我只是在列表中得到字符串,所以我不能将它们定义为列表:

    worksheets = []
    for i in range(len(master_test_list)):
        worksheets.append(str(i+1))
    worksheets = ["worksheet%s" % x for x in worksheets]
    testcases = ["testcases_list_%s" % x for x in master_test_list]
    results = ["results_%s" % x for x in master_test_list]
    screenshot_paths = ["screenshot_paths_%s" % x for x in master_test_list]
    
    for w in worksheets:
        w = workbook.add_worksheet('Results')
    for t in testcases:
        t = []
    for r in results:
        r = []
    for s in screenshot_paths:
        s = []
    

    你的解释留下了一些可以想象的东西,但我想我已经得到了你所需要的。有两个文件:.pypython文件和Excel文件,电子表格是添加纸张的基础。您可以找到我在github上制作的:

    这是excel代码。先分享,因为它比较短。如果您不想下载我的,请制作一张名为“AddSheets.xlsm”的表格,其中包含一个名为“SheetAdder”的模块,并在该模块中输入以下代码:

    Public Sub AddASheet(nm)
        
        Application.DisplayAlerts = False 'Reset on workbook open event, since we need it to be False here right up to the point of saving and closing
        
        Dim NewSheet As Worksheet
        
        Set NewSheet = ThisWorkbook.Sheets.Add
        NewSheet.Name = nm
        
    End Sub
    
    
    
    确保将其添加到VBA项目的“MicroSoft Excel对象”文件夹中的“ThisWorkbook”代码中:

    Private Sub Workbook_Open()
        Application.DisplayAlerts = True
    End Sub
    
    
    python脚本如下所示:

    请参见[此问题][1],了解如何将文件路径格式化为函数参数的字符串的示例。我把我的拿走了

    import win32com.client as wincl
    import os
    
    # Following modified from https://stackoverflow.com/questions/58188684/calling-vba-macro-from-python-with-unknown-number-of-arguments
    
    
    def run_vba_macro(str_path, str_modulename, str_macroname, shtNm):
        if os.path.exists(str_path):
            xl = wincl.DispatchEx("Excel.Application")
            wb = xl.Workbooks.Open(str_path, ReadOnly=0)
            xl.Visible = True
            xl.Application.Run(os.path.basename(str_path)+"!" +
                               str_modulename+'.'+str_macroname, shtNm)
            wb.Save()
            wb.Close()
            xl.Application.Quit()
            del xl
    
    
    # Insert your code which generates your list here
    list1 = ['backup', 'downloadMedia', 'createAlbum']
    
    # Dont make a new free floating list for each element of list1. Generate and store the lists you want in a dictionary
    testcases = dict([[x, []] for x in list1])
    results = dict([[x, []] for x in list1])
    screenshot_paths = dict([[x, []] for x in list1])
    
    for myContent in list1:
        myTestCaseList = []  # Do whatever you like to generate the data u need
        myResultsList = []
        myScreenshot_Paths_List = []
    
        # 1 Store your created list for test case of item 'myContent' from list1 in a dictionary
        testcases[myContent].append(myTestCaseList)
        # 2 Same but your results list
        results[myContent].append(myResultsList)
        # 3 Same but your screenshot_paths list
        screenshot_paths[myContent].append(myScreenshot_Paths_List)
        # 4 Make an excel sheet named after the item from list1
        run_vba_macro("C:\\Users\\xx-_-\\Documents\\Coding Products\\Python (Local)\\Programs\\Python X Excel\\AddSheets.xlsm",
                      "SheetAdder", "AddASheet", myContent)```
    
    I started working on this before you updated your question with a code sample, so bear in mind I haven't looked at your code at all lol. Just ran with this. 
    
    Here is a summary of what all of the above does:
    -Creates an excel sheet with a sheet for every element in 'list1', with the sheet named after that element
    -Generates 3 dictionaries, one for test cases, one for results, and one for screenshot paths, where each dictionary has a list for each element from 'list1', with that list as the value for the key being the element in 'list1'
    
    
      [1]: https://stackoverflow.com/questions/58188684/calling-vba-macro-from-python-with-unknown-number-of-arguments
    

    你的解释留下了一些可以想象的东西,但我想我已经得到了你所需要的。有两个文件:.pypython文件和Excel文件,电子表格是添加纸张的基础。您可以找到我在github上制作的:

    这是excel代码。先分享,因为它比较短。如果您不想下载我的,请制作一张名为“AddSheets.xlsm”的表格,其中包含一个名为“SheetAdder”的模块,并在该模块中输入以下代码:

    Public Sub AddASheet(nm)
        
        Application.DisplayAlerts = False 'Reset on workbook open event, since we need it to be False here right up to the point of saving and closing
        
        Dim NewSheet As Worksheet
        
        Set NewSheet = ThisWorkbook.Sheets.Add
        NewSheet.Name = nm
        
    End Sub
    
    
    
    确保将其添加到VBA项目的“MicroSoft Excel对象”文件夹中的“ThisWorkbook”代码中:

    Private Sub Workbook_Open()
        Application.DisplayAlerts = True
    End Sub
    
    
    python脚本如下所示:

    请参见[此问题][1],了解如何将文件路径格式化为函数参数的字符串的示例。我把我的拿走了

    import win32com.client as wincl
    import os
    
    # Following modified from https://stackoverflow.com/questions/58188684/calling-vba-macro-from-python-with-unknown-number-of-arguments
    
    
    def run_vba_macro(str_path, str_modulename, str_macroname, shtNm):
        if os.path.exists(str_path):
            xl = wincl.DispatchEx("Excel.Application")
            wb = xl.Workbooks.Open(str_path, ReadOnly=0)
            xl.Visible = True
            xl.Application.Run(os.path.basename(str_path)+"!" +
                               str_modulename+'.'+str_macroname, shtNm)
            wb.Save()
            wb.Close()
            xl.Application.Quit()
            del xl
    
    
    # Insert your code which generates your list here
    list1 = ['backup', 'downloadMedia', 'createAlbum']
    
    # Dont make a new free floating list for each element of list1. Generate and store the lists you want in a dictionary
    testcases = dict([[x, []] for x in list1])
    results = dict([[x, []] for x in list1])
    screenshot_paths = dict([[x, []] for x in list1])
    
    for myContent in list1:
        myTestCaseList = []  # Do whatever you like to generate the data u need
        myResultsList = []
        myScreenshot_Paths_List = []
    
        # 1 Store your created list for test case of item 'myContent' from list1 in a dictionary
        testcases[myContent].append(myTestCaseList)
        # 2 Same but your results list
        results[myContent].append(myResultsList)
        # 3 Same but your screenshot_paths list
        screenshot_paths[myContent].append(myScreenshot_Paths_List)
        # 4 Make an excel sheet named after the item from list1
        run_vba_macro("C:\\Users\\xx-_-\\Documents\\Coding Products\\Python (Local)\\Programs\\Python X Excel\\AddSheets.xlsm",
                      "SheetAdder", "AddASheet", myContent)```
    
    I started working on this before you updated your question with a code sample, so bear in mind I haven't looked at your code at all lol. Just ran with this. 
    
    Here is a summary of what all of the above does:
    -Creates an excel sheet with a sheet for every element in 'list1', with the sheet named after that element
    -Generates 3 dictionaries, one for test cases, one for results, and one for screenshot paths, where each dictionary has a list for each element from 'list1', with that list as the value for the key being the element in 'list1'
    
    
      [1]: https://stackoverflow.com/questions/58188684/calling-vba-macro-from-python-with-unknown-number-of-arguments
    

    添加第二个答案,因为代码明显不同,解决了如何创建n份列表副本的指定请求:

    def GenerateElements():
        # Insert your code which generates your list here
        myGeneratedList = ['backup', 'downloadMedia', 'createAlbum']
        return myGeneratedList
    
    
    def InitDict(ListOfElements):
        # Dont make a new free floating list for each element of list1. Generate and store the lists you want in a dictionary
        return dict([[x, []] for x in ListOfElements])
    
    
    def RunTest():
        for myContent in list1:
            # Do whatever you like to generate the data u need
            myTestCaseList = ['a', 'b']
            myResultsList = [1, 2]
            myScreenshot_Paths_List = ['sc1', 'sc2']
    
            # 1 Store your created list for test case of item 'myContent' from list1 in a dictionary
            testcases[myContent].append(myTestCaseList)
            # 2 Same but your results list
            results[myContent].append(myResultsList)
            # 3 Same but your screenshot_paths list
            screenshot_paths[myContent].append(myScreenshot_Paths_List)
            # 4 Make an excel sheet named after the item from list1
            # run_vba_macro("C:\\Users\\xx-_-\\Documents\\Coding Products\\Python (Local)\\Programs\\Python X Excel\\AddSheets.xlsm","SheetAdder", "AddASheet", myContent)
    
    
    list1 = GenerateElements()
    testcases, results, screenshot_paths = InitDict(
        list1), InitDict(list1), InitDict(list1)
    
    NumTests = 5  # Number of tests you want
    for x in range(NumTests):
        RunTest()
    
    这里要做的只是定义一些初始化函数,然后在几行中使用它们

    我的理解是,您正在运行一系列测试,其中您希望输入和输出的列表是一种运行计数类型的东西。因此,此代码使用字典存储列表列表。字典的关键是如何识别您正在查看的日志:测试用例日志、结果日志、屏幕截图和路径日志

    根据我对您需求的理解,每个dictionary元素都是一个列表列表,其中第一个列表只是第一次测试的输出。第二个列表是第一个列表,其中附加了第二个测试/结果的结果。这样下去,结构看起来像:

    testcases= [ [testcase1] , [testcase1,testcase2] , [testcase1,testcase2,testcase3] ]
    
    等等


    如果这不完全是您想要的,您可能可以修改它以满足您的需要。

    添加第二个答案,因为代码明显不同,解决如何创建n个列表副本的指定请求:

    def GenerateElements():
        # Insert your code which generates your list here
        myGeneratedList = ['backup', 'downloadMedia', 'createAlbum']
        return myGeneratedList
    
    
    def InitDict(ListOfElements):
        # Dont make a new free floating list for each element of list1. Generate and store the lists you want in a dictionary
        return dict([[x, []] for x in ListOfElements])
    
    
    def RunTest():
        for myContent in list1:
            # Do whatever you like to generate the data u need
            myTestCaseList = ['a', 'b']
            myResultsList = [1, 2]
            myScreenshot_Paths_List = ['sc1', 'sc2']
    
            # 1 Store your created list for test case of item 'myContent' from list1 in a dictionary
            testcases[myContent].append(myTestCaseList)
            # 2 Same but your results list
            results[myContent].append(myResultsList)
            # 3 Same but your screenshot_paths list
            screenshot_paths[myContent].append(myScreenshot_Paths_List)
            # 4 Make an excel sheet named after the item from list1
            # run_vba_macro("C:\\Users\\xx-_-\\Documents\\Coding Products\\Python (Local)\\Programs\\Python X Excel\\AddSheets.xlsm","SheetAdder", "AddASheet", myContent)
    
    
    list1 = GenerateElements()
    testcases, results, screenshot_paths = InitDict(
        list1), InitDict(list1), InitDict(list1)
    
    NumTests = 5  # Number of tests you want
    for x in range(NumTests):
        RunTest()
    
    这里要做的只是定义一些初始化函数,然后在几行中使用它们

    我的理解是,您正在运行一系列测试,其中您希望输入和输出的列表是一种运行计数类型的东西。因此,此代码使用字典存储列表列表。字典的关键是如何识别您正在查看的日志:测试用例日志、结果日志、屏幕截图和路径日志

    根据我对您需求的理解,每个dictionary元素都是一个列表列表,其中第一个列表只是第一次测试的输出。第二个列表是第一个列表,其中附加了第二个测试/结果的结果。这样下去,结构看起来像:

    testcases= [ [testcase1] , [testcase1,testcase2] , [testcase1,testcase2,testcase3] ]
    
    等等


    如果这不完全是您想要的,您可以修改它以满足您的需要。

    到目前为止,这看起来像是一个伪代码,请发布代码并显示您的尝试。我发布了我想到的任何东西,但这不起作用。我对字典没有太多的经验……有人能帮我吗?甚至只是给我指出正确的方向。我现在对字典的概念有了更多的了解……但我不明白这将如何让我形成一个列表,我将在我的脚本中不断添加它。基本上,这就是我需要的:1。根据列表1的长度,创建3个列表的n个副本。2.使用工作表\u i=工作簿创建n个工作表。添加工作表(“结果”)。到目前为止,这看起来像一个伪代码,请发布代码并显示您的尝试。我发布了我想到的任何内容,但不起作用。我对字典没有太多的经验……有人能帮我吗?甚至只是给我指出正确的方向。我现在对字典的概念有了更多的了解……但我不明白这将如何让我形成一个列表,我将在我的脚本中不断添加它。基本上,这就是我需要的:1。根据列表1的长度,创建3个列表的n个副本。2.使用工作表i=工作簿创建n个工作表。添加工作表('R