Yield in a recursive function

后端 未结 9 703
独厮守ぢ
独厮守ぢ 2021-01-30 10:49

I am trying to do something to all the files under a given path. I don\'t want to collect all the file names beforehand then do something with them, so I tried this:

<         


        
9条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-30 11:01

    You can also implement the recursion using a stack.

    There is not really any advantage in doing this though, other than the fact that it is possible. If you are using python in the first place, the performance gains are probably not worthwhile.

    import os
    import stat
    
    def explore(p):
        '''
        perform a depth first search and yield the path elements in dfs order
            -implement the recursion using a stack because a python can't yield within a nested function call
        '''
        list_t=type(list())
        st=[[p,0]]
        while len(st)>0:
            x=st[-1][0]
            print x
            i=st[-1][1]
    
            if type(x)==list_t:
                if i>=len(x):
                    st.pop(-1)
                else:
                    st[-1][1]+=1
                    st.append([x[i],0])
            else:
                st.pop(-1)
                stat_info = os.lstat(x)
                if stat.S_ISDIR(stat_info.st_mode):
                    st.append([['%s/%s'%(x,a) for a in os.listdir(x)],0])
                else:
                    yield x
    
    print list(explore('.'))
    

提交回复
热议问题