Python 如何将未指定数量的列表附加到列表

Python 如何将未指定数量的列表附加到列表,python,list,append,Python,List,Append,我的任务是创建一个列表,其中包含搜索目录文件夹中所有sql文件的相对和绝对路径 问题是我无法事先知道主列表应该包含多少文件 有没有办法在跑步时附加列表 cnt_of_sql_files = 0 for dirpath, subdirs, files in walk(search_dir): for file in files: if file.endswith('.sql'): cnt_of_sql_files +=1 scripts = [[

我的任务是创建一个列表,其中包含搜索目录文件夹中所有sql文件的相对和绝对路径

问题是我无法事先知道主列表应该包含多少文件

有没有办法在跑步时附加列表

cnt_of_sql_files = 0

for dirpath, subdirs, files in walk(search_dir):
    for file in files:
        if file.endswith('.sql'):
            cnt_of_sql_files +=1

scripts = [[]] * cnt_of_sql_files 

for dirpath, subdirs, files in walk(search_dir):
    for file in files:
        if file.endswith('.sql'):
            for index in range(cnt_of_sql_files):
                scripts[index] = [path.join(dirpath, file),
                              path.join(path.basename(dirpath), file)]
print(scripts)

你不需要知道。只需使用append方法添加所有必要的内容:

scripts = [] 

for dirpath, subdirs, files in walk(search_dir):
    for file in files:
        if file.endswith('.sql'):
            scripts.append([path.join(dirpath, file),
                           path.join(path.basename(dirpath), file)])
print(scripts)

使用python列表时,可以使用append和extend list方法向列表中添加任意数量的元素

list1.appendlist2-将list2作为列表添加到list1的末尾

list1.extendlist2-将列表2中的项目作为单个项目添加到列表1的末尾

因为您需要一个列表列表,所以我们使用append

另外,为了找到文件的相对路径, 通过path.relpathdirpath、search_dir查找search dirpath相对于search_dir的相对路径,然后使用path.joinpath.relpathdirpath、search_dir、file将路径与文件连接起来更为正确

以下代码应该可以解决您的问题:

search_dir = "C:\Users\Tanuja\PycharmProjects\practice\practice problems"
    scripts = []
    for dirpath, subdirs, files in walk(search_dir):
        for file in files:
            if file.endswith('.sql'):
                scripts.append([path.join(dirpath, file), path.join(path.relpath(dirpath, search_dir), file)])
    print(scripts)
要使代码更具python风格,可以使用列表理解:

    scripts = []
    for dirpath, subdirs, files in walk(search_dir):
        scripts.extend([[path.join(dirpath, file), path.join(path.relpath(dirpath, search_dir), file)] for file in files if file.endswith('.sql')])
    print scripts

... 是的,您使用.append方法。因此,只需使用scripts=[],然后在循环中只需执行scripts.append[path.joindirpath,file,path.joinpath.basenamedirpath,file]。您的最终示例输出是什么?