简体   繁体   English

如何跳过序列的其余部分

[英]how to skip the rest of a sequence

I have a couple of functions that are being called recursively inside nested loops. 我有几个在嵌套循环中递归调用的函数。 The ultimate objective of my program is to: 我的计划的最终目标是:

a) loop through each year, a)每年循环一次,
b) within each each year, loop through each month (12 total), b)在每年的每年中,循环浏览每个月(共12个),
c) within each month, loop through each day (using a self generated day counter), c)在每个月之内,遍历每一天(使用自行生成的天数计数器),
d) and read 2 files and merge them together into a another file. d)读取2个文件并将它们合并到另一个文件中。

In each instance, I am going down into the directory only if exists. 在每种情况下,只有存在时,我才会进入目录。 Otherwise, I'm to just skip it and go to the next one. 否则,我将跳过它并转到下一个。 My code does a pretty good job when all the files are present, but when one of the files is missing, I would like to just simply skip the whole process of creating a merged file and continue the loops. 当所有文件都存在时,我的代码做得很好,但是当其中一个文件丢失时,我只想跳过创建合并文件的整个过程并继续循环。 The problem I am getting is a syntax error that states that continue is not properly in the loop. 我遇到的问题是语法错误,指出continue操作在循环中不正确。 I am only getting this error in the function definitions, and not outside of them. 我只在函数定义中收到此错误,而不是在它们之外。

Can someone explain why I'm getting this error? 有人可以解释为什么我会收到此错误吗?

import os, calendar

file01 = 'myfile1.txt'
file02 = 'myfile2.txt'
output = 'mybigfile.txt'

def main():
    #ROOT DIRECTORY
    top_path = r'C:\directory'    
    processTop(top_path)

def processTop(path):
    year_list = ['2013', '2014', '2015']

    for year in year_list:
        year_path = os.path.join(path, year)
        if not os.path.isdir(year_path):  
            continue
        else:
            for month in range(1, 13):
                month_path = os.path.join(year_path, month)
                if not os.path.isdir(month_path):
                    continue
                else:
                    numDaysInMth = calendar.monthrange(int(year), month)[1]
                    for day in range(1, numDaysInMth+1):
                        processDay(day, month_path)
    print('Done!')


def processDay(day, path):
    day_path = os.path.join(path, day)
    if not os.path.isdir(day_path):
        continue
    else:
        createDailyFile(day_path, output)


def createDailyFile(path, dailyFile):
    data01 = openFile(file01, path)
    data02 = openFile(file02, path)

    if len(data01) == 0 or len(data02) == 0: 
        # either file is missing
        continue
    else:
        # merge the two datalists into a single list
        # create a file with the merged list
        pass

def openFile(filename, path):
    # return a list of contents of filename
    # returns an empty list if file is missing
    pass

if __name__ == "__main__": main()

You are probably getting that error in processDay and createDailyFile , right? 您可能在processDaycreateDailyFile收到该错误,对吗? That's because there is no loop in these functions, and yet you use continue . 这是因为这些函数中没有循环,但是您可以使用continue I'd recommend using return or pass in them. 我建议使用returnpass

当错误消息表明如果函数的结构如您所显示的那样,仅可以使用passcontinue语句仅在循环中适用。

continue can only appear in a loop since it tells python not to execute the lines below and go to the next iteration. 连续只能出现在循环中,因为它告诉python不要执行下面的行并转到下一个迭代。 Hence, this syntax here is not valid : 因此,此语法无效:

def processDay(day, path):
    day_path = os.path.join(path, day)
    if not os.path.isdir(day_path):
        continue # <============ this continue is not inside a loop !
    else:
        createDailyFile(day_path, output)enter code here

Same for your createDailyFile function. 与您的createDailyFile函数相同。

You may want to replace it with a return ? 您可能要用退货替换它?

You can use continue only plainly inside a loop (otherwise, what guarantee you have that the function was called in a loop in the first place?) If you need stack unwinding, consider using exceptions ( Python exception handling ). 您只能在循环内简单地使用continue (否则,首先确保在循环中调用该函数的保证是什么?)如果需要堆栈展开,请考虑使用异常( Python异常处理 )。

I think you can get away with having your functions return a value that would say if operation was completed successfully: 我认为您可以避免让函数返回一个值,该值表示操作是否成功完成:

def processDay(day, path):
  do_some_job()
  if should_continue:
     return False
  return True

And then in your main code simply say 然后在您的主代码中简单地说

if not processDay(day, path):
  continue

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何跳过一列并将其余的相乘? - how to skip a column and multiply the rest? 如果一个失败,如何跳过课堂上的其他测试? - How to skip the rest of tests in the class if one has failed? 如何跳过列表中的某些索引并在 python 中传播其余索引 - How do I skip some indexes in a list and spread the rest in python 如何在 function 本身的特定条件后跳过 function 的 rest - How to skip the rest of function after a specific condition in the function itself 与 cv2.videocapture() 一起使用时如何跳过图像序列中丢失的图像/帧? - How to skip missing images/frames within an image sequence when used with cv2.videocapture()? 对于语句增量并跳过代码的 rest - For statement increment and skip the rest of the code pyparsing优化跳过rest的行 - pyparsing optimize skip rest of line Python bs4抓取,如何在列表中查找某些类并跳过但抓取其余部分 - Python bs4 Scraping, how to find certain Class in a List and skip but scrape rest 如何跳过行,直到在txt文件中找到“关键字”并将其余内容另存为csv? 蟒蛇 - How to skip lines until find the 'keyword' in txt file and save rest as csv? python Python, Pandas: How to automatically skip Excel header cells and add the rest to a dataframe - Python, Pandas: How to automatically skip Excel header cells and add the rest to a dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM