【问题标题】:appending to a list inside a loop using a variable as the list name使用变量作为列表名称附加到循环内的列表
【发布时间】:2022-01-20 17:43:23
【问题描述】:

我的目标是从几个文件的内容中创建几个列表。过去,我在循环内部使用 '{}'.format(x) 作为更改循环内部路径以匹配循环正在处理的列表中的任何项目的方法。现在我想将其扩展到附加到循环外的列表。这是我目前使用的代码。

import csv
import os

c3List = []
c4List = []
camList = []
plantList = ('c3', 'c4', 'cam')

for p in plantList:
    plantFolder = folder path
    plantCsv = '{}List.csv'.format(p)
    plantPath = os.path.join(plantFolder, plantCsv)
    with open(plantPath) as plantParse:
        reader = csv.reader(plantParse)
        data = list(reader)
        '{}List'.format(p).append(data)

但这给了我 AttributeError: 'str' object has no attribute 'append'

如果我尝试制作这样的变量

pList = '{}List'.format(p)
pList.append(data)

我得到同样的错误。任何意见,将不胜感激。我正在使用 Python 3。

【问题讨论】:

  • str.format() 返回一个没有.append()字符串。您不能简单地通过创建其名称的字符串来引用变量
  • 这可能与您的问题有关:How do I create a variable number of variables
  • 我希望它第一次循环通过它以获取 c3List.csv 中的项目并将其添加到 c3List,然后 c4List.csv 并添加到 c4List,然后 camList.scv 并添加到 camList。我会查看您提供的变量链接,看看我能找到什么。
  • 这能回答你的问题吗? How do I create variable variables?

标签: python-3.x list loops format append


【解决方案1】:

因为列表对象是可变的,您可以创建一个引用所有列表的字典。

例如:

myList = []
myDict = {"a": myList}

myDict["a"].append("appended_by_reference")
myList.append("appended_directly")

print(myList)

您将得到['appended_by_reference', 'appended_directly'] 打印。

如果您想了解更多关于 python 中的 mutabilityimmutability 的信息,请参阅link

所以我自己实现目标的实现是:

import csv
from pathlib import Path

c3List = []
c4List = []
camList = []
plantList = {'c3': c3List, 'c4': c4List, 'cam': camList}

plantFolder = `folder path`
for p in plantList:
    plantCsv = f'{p}List.csv'
    plantPath = Path(plantFolder, plantCsv)
    with open(plantPath) as plantParse:
        reader = csv.reader(plantParse)
        data = list(reader)
        plantList[p].append(data)

注意:我使用fstring 来格式化字符串并使用pathlib 来定义文件路径

【讨论】:

    猜你喜欢
    • 2014-01-11
    • 2016-05-13
    • 2015-08-23
    • 1970-01-01
    • 2020-01-16
    • 2022-07-06
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多