gpt4 book ai didi

python - 简单的列表理解

转载 作者:太空宇宙 更新时间:2023-11-03 12:29:39 24 4
gpt4 key购买 nike

我想要一个文件字典:

files = [files for (subdir, dirs, files) in os.walk(rootdir)]

但是我明白了,

files = [['filename1', 'filename2']] 

当我想要的时候

files = ['filename1', 'filename2']

如何防止循环遍历该元组?谢谢!

最佳答案

这两个工作:

[f for (subdir, dirs, files) in os.walk(rootdir) for f in files]

sum([files for (subdir, dirs, files) in os.walk(rootdir)], [])

示例输出:

$ find /tmp/test
/tmp/test
/tmp/test/subdir1
/tmp/test/subdir1/file1
/tmp/test/subdir2
/tmp/test/subdir2/file2
$ python
>>> import os
>>> rootdir = "/tmp/test"
>>> [f for (subdir, dirs, files) in os.walk(rootdir) for f in files]
['file1', 'file2']
>>> sum([files for (subdir, dirs, files) in os.walk(rootdir)], [])
['file1', 'file2']

关于python - 简单的列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3326428/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com