【问题标题】:Appending from a csv file for each time a function is called每次调用函数时从 csv 文件中追加
【发布时间】:2018-04-29 00:01:46
【问题描述】:

如何在每次迭代时将某些内容附加到列表中的变量? 我需要能够根据调用函数的次数添加一个数字。例如,如果该函数被调用 3 次,则将调用 csv 列表中的某一行,并将该数字附加到列表中。例如,此处的个人列表看起来像 ['john', '1', '这里将添加数字'。

personList = []

def number(peopleList):
    personList.append(peopleList[:])
    return personList

如果这真的没有意义,请致歉!发现很难清楚地表达我在这里想要实现的目标。但是感谢您的关注:)

【问题讨论】:

    标签: python list function csv append


    【解决方案1】:

    如果我正确理解了您的问题,您希望将增量计数器附加到要添加到 personList 的每个 peopleList 对象。

    使用您的代码示例,一个好的解决方案是让您声明一个全局变量并在每次调用您的函数时递增它,同时将其附加到peopleList

    personList = []
    functionCalls = 0
    
    def number(peopleList):
        global functionCalls
        functionCalls += 1
    
        # if peopleList is ['john', '1'] then ['john', '1', NUMBER_OF_CALLS] will be appended here.
        personList.append(peopleList[:] + [functionCalls]) 
        return personList
    

    【讨论】:

    • def number(peopleList): global functionCalls functionCalls += 1 with open('numbers.csv', 'r') as csvfile: reader = csv.reader(csvfile) numbersList = list(reader) personList.append(peopleList[:] + [functionCalls]) print(personList) return personList 感谢您这么快回复!我试图在我的代码中实现你所说的,但是问题是每次都将 csv 列表中的元素添加到每个元素中。例如 ['John', '1', 'Sam', '2'], ['Jack', '1', 'Joe', '2'], 1]]
    • CSV 文件看起来像这样 10, 20, 30, 40, 50
    • 这很难理解你想在这里实现什么...你如何调用函数numberpeopleList 变量包含什么?
    猜你喜欢
    • 1970-01-01
    • 2015-11-21
    • 2020-03-25
    • 2020-09-06
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    相关资源
    最近更新 更多