简体   繁体   English

分组项目 Python

[英]Grouping Items Python

Let's say I have multiple unknown number of strings in a file.假设我在一个文件中有多个未知数量的字符串。 Every string is written in a new line.每个字符串都写在一个新行中。 eg.例如。

John, Task = Coding Challenge, Status = Not Completed

Kevin, Task = Compile, Status = Completed

John, Task = Fix Bug, Status = Completed

...etc

Exactly in this format,nevermind the spacing between lines its for readability正是在这种格式中,为了便于阅读,不要介意行间距

We don't know how many times John or Kevin will show up in this file.我们不知道 John 或 Kevin 会在这个文件中出现多少次。 I want to group every single line according to their names, and provide the info in a user friendly manner.我想根据他们的名字对每一行进行分组,并以用户友好的方式提供信息。 eg.例如。

name = John

no. of tasks = 2

completed tasks = 1

etc...

Fairly new to programming, reason there's no code is because I don't even know where to start, I Understand basic Python (opening the text file, and iterating through the file).对编程相当陌生,没有代码的原因是因为我什至不知道从哪里开始,我了解基本的 Python(打开文本文件,并遍历文件)。 It is the next steps that follow after.这是之后的下一步。 Asking for steps and guidance really but a solution of the above example is also very much appreciated.确实要求步骤和指导,但也非常感谢上述示例的解决方案。

This is one approach using csv module to process the file and dict to store the data这是一种使用csv模块处理文件和dict来存储数据的方法

Ex:前任:

import csv

result = {}
with open(filename) as infile:
    reader = csv.reader(infile)
    for name, *line in reader:
        completed = 1 if line[-1].endswith("Completed") else 0
        if name not in result:
            result[name] = {'name': name, 'tasks': 1, 'completed_tasks': completed}
        else:
            result[name]['tasks'] += 1
            result[name]['completed_tasks'] += completed

print(list(result.values()))

Output: Output:

[{'completed_tasks': 2, 'name': 'John', 'tasks': 2}, 
 {'completed_tasks': 1, 'name': 'Kevin', 'tasks': 1}]

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

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