简体   繁体   English

Python - 循环遍历列表中的一组项目

[英]Python - Looping through a set of items in a list

I have the below query that extract some data from JIRA and have that saved to a csv. 我有以下查询从JIRA中提取一些数据并将其保存到csv。 I am however trying to loop in through a series of projects. 然而,我正试图通过一系列项目。 I see that the latest project gets saved and not all projects passed in the loop. 我看到最新项目得到了保存,而不是所有项目都在循环中传递。

Given below is what I am trying to perform : 以下是我正在尝试执行的操作:

projects = ['project_a','project_b']

for project in projects:
    issues = jira.search_issues('project= ' + project)

    result = []
    for value in issues:
        value = value
        timeSpentSeconds = i.timeSpentSeconds
        timeSpent = i.timeSpent
        updated = i.updated
        started = i.started
        author = i.author
        dict_ = {'value': value,
                     'timeSpent': timeSpent,
                     'updated': updated,
                     'started': started,
                     'author': author}

        result.append(dict_)

        df = pd.DataFrame(result)


        df.to_csv('/Desktop/file.csv')

You're overwriting the data frame at each loop df.to_csv('/Desktop/file.csv') . 你在每个循环df.to_csv('/Desktop/file.csv')覆盖数据帧。 Everytime, you write the new project in the file and erase the old one. 每次,您在文件中编写新项目并删除旧项目。

You should define result before starting to iterate over the projects. 您应该在开始迭代项目之前定义结果。 Otherwise, you can create one csv file per project. 否则,您可以为每个项目创建一个csv文件。

Also it would be more efficient to create and save the dataframe at the end of the top level loop. 此外,在顶级循环结束时创建和保存数据帧会更有效。

df.to_csv('/Desktop/file.csv', mode='a')

Default mode of .to_csv is write. 写入.to_csv的默认模式。 You have to change it to append. 你必须改变它才能追加。 If you want to do it that way. 如果你想这样做。

Better solution would be to make whole dataframe then saving it to wanted file 更好的解决方案是制作整个数据帧,然后将其保存到想要的文件

projects = ['project_a','project_b']

result = []

for project in projects:
    issues = jira.search_issues('project= ' + project, maxResults=False, fields="worklog")   
    for value in issues:
        for i in value.fields.worklog.worklogs:
            value = value
            timeSpentSeconds = i.timeSpentSeconds
            timeSpent = i.timeSpent
            updated = i.updated
            started = i.started
            author = i.author
            dict_ = {'value': value,
                     'timeSpent': timeSpent,
                     'updated': updated,
                     'started': started,
                     'author': author}

            result.append(dict_)

df = pd.DataFrame(result)
df.to_csv('/Desktop/file.csv')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM