分组项目Python
假设一个文件中有多个未知数量的字符串。每个字符串都写在新行中。 例如 正是在这种格式中,为了便于阅读,不必考虑行间距 我们不知道John或Kevin会在这个文件中出现多少次。我想根据每一行的名称对它们进行分组,并以用户友好的方式提供信息。例如分组项目Python,python,list,dictionary,Python,List,Dictionary,假设一个文件中有多个未知数量的字符串。每个字符串都写在新行中。 例如 正是在这种格式中,为了便于阅读,不必考虑行间距 我们不知道John或Kevin会在这个文件中出现多少次。我想根据每一行的名称对它们进行分组,并以用户友好的方式提供信息。例如 name = John no. of tasks = 2 completed tasks = 1 etc... 对于编程来说相当陌生,之所以没有代码是因为我甚至不知道从哪里开始,我理解基本的Python打开文本文件,并遍历文件。这是接下来的步骤。确
name = John
no. of tasks = 2
completed tasks = 1
etc...
对于编程来说相当陌生,之所以没有代码是因为我甚至不知道从哪里开始,我理解基本的Python打开文本文件,并遍历文件。这是接下来的步骤。确实需要步骤和指导,但也非常感谢上述示例的解决方案。这是一种使用csv模块处理文件和dict存储数据的方法 例: 输出:
请尝试并分享您的代码,然后再询问查看python库。它具有陡峭的学习曲线,但可以说是python在表管理和csv支持方面最好的库。它也非常畅销。
name = John
no. of tasks = 2
completed tasks = 1
etc...
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()))
[{'completed_tasks': 2, 'name': 'John', 'tasks': 2},
{'completed_tasks': 1, 'name': 'Kevin', 'tasks': 1}]