【问题标题】:How to append unspecified amount of lists to list如何将未指定数量的列表附加到列表中
【发布时间】:2019-07-27 19:34:12
【问题描述】:

我的任务是创建一个列表列表,其中包含我的 search_dir 文件夹中所有 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 = [],然后在您的循环中执行scripts.append([path.join(dirpath, file), path.join(path.basename(dirpath), file)]
  • 您的最终样本输出是什么?

标签: python list append


【解决方案1】:

你不需要知道。只需使用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)

【讨论】:

    【解决方案2】:

    使用 python 列表时,您可以使用追加和扩展列表方法将任意数量的元素添加到列表中

    list1.append(list2) -- 在list1的末尾添加list2作为列表

    list1.extend(list2) -- 将list2中的项目添加到list1的末尾作为单独的项目

    由于您需要一个列表列表,我们将使用附加。

    另外,为了找到文件的相对路径, 通过path.relpath(dirpath, search_dir)找到搜索目录相对于search_dir的相对路径,然后使用path.join(path.relpath(dirpath, 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)
    

    为了让你的代码更 Pythonic,你可以使用列表推导:

        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
    

    【讨论】:

      猜你喜欢
      • 2013-02-04
      • 2013-03-08
      • 1970-01-01
      • 2018-04-25
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      相关资源
      最近更新 更多