gpt4 book ai didi

Python 嵌套循环

转载 作者:行者123 更新时间:2023-12-01 06:03:56 28 4
gpt4 key购买 nike

您好,我是 python 新手,有一个关于执行嵌套循环的最佳/pythonic 方法的问题。

我想将每个目录放入一个数组中,并使用该目录中包含的文件的嵌套数组。

我一直在研究 python 数组、字典、集合和元组,但不确定执行此操作的最佳方法

[注意我只想在一个级别上执行此操作,而不是递归地遍历所有目录]

目前我有一个函数将子目录的所有文件添加到一个数组中,但现在我也需要返回它们的父文件夹。

提前致谢

    def getffdirs():

filedirs = []

path = os.curdir

for d in os.listdir(path):

if os.path.isdir(d):
print("Entering " + d)

curPath = os.path.join(path, d)
for f in os.listdir(curPath):

if os.path.isfile(f):
print("file " + f)
filedirs.append(f)
return filedirs

最佳答案

我会使用字典来实现此目的,键将是目录和文件的值列表:

def getffdirs():

dirs = {}
path = os.curdir
for d in os.listdir(path):

if os.path.isdir(d):
print("Entering " + d)
dirs[d] = [] # add directory with empty list

curPath = os.path.join(path, d)
for f in os.listdir(curPath):

if os.path.isfile(f):
print("file " + f)
dirs[d].append(f) # add files to appropriate directory
return dirs

访问数据:

for dir,files in dirs.items(): # notice the call to dirs.items(), thats what was missing.
print "directory: ",dir
print "files:"
for f in files:
print f

关于Python 嵌套循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8996500/

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