简体   繁体   English

python遍历列表

[英]python iterating over list

I try to iterate over each item in the list. 我尝试遍历列表中的每个项目。 But iterator does not go through all objects. 但是迭代器不会遍历所有对象。 Here is my function code(dirs and root comes from os.walk) 这是我的功能代码(dirs和root来自os.walk)

def remove_hidden_dirs(dirs,root):
    """
    Function remove hidden directories . .. in unix
    """
    logging.debug("\n\n remove hidden" )
    logging.debug('Start removing hidden dirs for %s',root)
    logging.debug("Length of dirs %s",len(dirs))
    logging.debug('File list before removing')
    dirs.sort()
    for d in dirs:
        logging.debug(d)
    i=0
    for d in dirs:
        i=i+1
        logging.debug("Iterating over %s",d)
        if d[0:1] == '.' or d[0:2] =='..':
            dirs.remove(d)
            logging.debug("Dir %s is being removed because of being hidden dir",d)
        else:
            logging.debug("Dir %s is NOT being removed because of being hidden dir",d)
    logging.debug("Iterate on %s", i)
    logging.debug('File list after removing')
    for d in dirs:
        logging.debug(d)
    logging.debug('end remove hidden files\n\n')
    return dirs

And here is part of my log.file 这是我的log.file的一部分

DEBUG:root:Start removing hidden dirs for /home/artur/
DEBUG:root:Length of dirs 38
DEBUG:root:File list before removing
DEBUG:root:.adobe
DEBUG:root:.android
DEBUG:root:.cache
DEBUG:root:.config
DEBUG:root:.dbus
...
DEBUG:root:Iterate on 22 dirs
DEBUG:root:File list after removing
DEBUG:root:.adobe
DEBUG:root:.cache
DEBUG:root:.dbus
...

Thanks in advance for any help 预先感谢您的任何帮助

Don't modify lists while iterating over them. 在迭代列表时不要修改列表。 Instead, produce a new list with just the items that you want to keep. 相反,仅生成要保留的项目的新列表。

dirs = [d for d in dirs if not d.startswith('.')]

Is an efficient simple and readable technique for doing it. 是一种有效的简单易读的技术。

Very simple: you are removing the current item from dirs while iterating over it. 很简单:您正在迭代中从dirs中删除当前项目。 That means you skip two forward on the next loop. 这意味着您在下一个循环中向前跳过两个。 See here . 这里

If what I said wasn't clear, say you iterate over this list of numbers: 如果我所说的内容不清楚,请说您遍历以下数字列表:

[1, 2, 3, 4, 5, 6...]
 ^

That's the state of the list initially; 最初是列表的状态; then 1 is removed and the loop goes to the second item in the list: 然后删除1然后循环转到列表中的第二项:

[2, 3, 4, 5, 6...]
    ^

Since you've removed 1 and moved forward by one in the list, now you're at 3 , not 2 . 由于您已删除1 在列表中向前移动了一个,所以现在您位于3 ,而不是2

[2, 4, 5, 6...]

Then you remove 3 ... and so on. 然后删除3 ...,依此类推。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM