python list comprehensions; compressing a list of lists?

后端 未结 13 1980
名媛妹妹
名媛妹妹 2020-11-30 01:49

guys. I\'m trying to find the most elegant solution to a problem and wondered if python has anything built-in for what I\'m trying to do.

What I\'m doing is this. I

13条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-30 02:06

    You can have nested iterations in a single list comprehension:

    [filename for path in dirs for filename in os.listdir(path)]
    

    which is equivalent (at least functionally) to:

    filenames = []
    for path in dirs:
        for filename in os.listdir(path):
            filenames.append(filename)
    

提交回复
热议问题