【问题标题】:How to loop through two elements simultaneously?如何同时循环两个元素?
【发布时间】:2020-11-22 17:35:31
【问题描述】:

我想在 python 中使用 for 循环同时遍历两个列表,因为我将使用 filecmp 比较它们的内容,如果文件内容相同则跳到下一次迭代。所以我希望两者都从索引 0 开始,这种工作语法是否有效,最好的方法是什么?

file_list = glob.glob(os.path.join(os.getcwd(), "../pythonProject", "*.json"))
duplicated_File_List = glob.glob(os.path.join(os.getcwd(), "../pythonProject/executed_Configs", "*.json"))

 for file_Path, test in file_list, duplicated_File_List:
    with open(file_Path) as jsonfile:            
        monitor_Data = json.load(jsonfile)
        logging.info("Read successful")
        while i < length:
            if filecmp.cmp(file_Path, test, shallow=True):
                i += 1
            continue

其中file_Pathfile_list 中的单个文件元素,testduplicated_File_List 中的单个元素。

【问题讨论】:

    标签: python-3.x for-loop


    【解决方案1】:
    for file_Path in file_list:
        for test in duplicated_File_List:
            #then u can type whatever u want to do with file_Path and test
    

    【讨论】:

    • 这将为外循环的每次迭代迭代内循环的所有项目,这意味着 MxN 迭代而不是 m 迭代(假设两个数组的长度相同......)
    【解决方案2】:

    如果您在 for 循环中向我们展示的是具有相同长度的可迭代对象,您可以这样做来循环:

     for file_Path, test in zip(file_list, duplicated_File_List):
          # rest of your code ...
    

    我仍然不明白你的内部 while 循环的建议是什么......

    【讨论】:

    • 压缩文件不会将每个列表的内容作为一个单元保存吗?
    • 您希望循环运行多少时间?我认为它不够清楚.. 使用 zip 假设两个列表长度相同,您只需迭代一次...
    • 哦,好吧,我只是不明白 zip 功能是如何工作的。我在想当使用 zip 时它会将两个文件存储到一个文件中。
    猜你喜欢
    • 2020-01-07
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-21
    • 2020-10-03
    • 2022-06-12
    • 2022-01-13
    相关资源
    最近更新 更多