【问题标题】:Naming a list in python using a String name使用字符串名称在 python 中命名列表
【发布时间】:2019-07-13 16:53:49
【问题描述】:

有谁知道在 python 中使用字符串命名列表的方法。我正在编写一个脚本,它遍历一个目录并解析每个文件并生成包含文件内容的列表。我想使用文件名来命名每个数组。我想知道是否有一种类似于 exec() 方法但使用列表而不是普通变量的方法

【问题讨论】:

  • 将其作为键存储在字典中。有关详细信息,请参阅this question

标签: python arrays string list


【解决方案1】:

如果你真的想这样做,那么例如:

import os
directory = os.getcwd()  # current directory or any other you would like to specify
for name in os.listdir(directory):
    globals()[name] = []

现在可以使用文件名引用每个列表。当然,这是一种次优方法,通常您应该使用其他数据结构(例如字典)来执行您的任务。

【讨论】:

    【解决方案2】:

    最好还是用字典。将文件名存储为字典的键值,并将内容放在键的对应值中。

    就像 my_dict = {'file1.txt':'This is the contents of file1','file2.txt':'This is the content of file2'}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 2019-09-01
      • 2013-03-11
      • 1970-01-01
      • 2015-10-29
      • 2021-11-26
      • 2019-06-24
      相关资源
      最近更新 更多