简体   繁体   English

计算列表中与 python 字典中的键对应的项目数

[英]Count the number of items in a list that correspond with a key in a dictionary in python

Good morning/evening, thank you for taking the time to read this.早上好/晚上好,感谢您花时间阅读本文。

I'm a beginner at programming and as part of a coding bootcamp project, I have to create a program to extract data from two.txt files in python, a file with 'user' data and a file with 'task' data.我是编程初学者,作为编码训练营项目的一部分,我必须创建一个程序来从 python 中的 two.txt 文件中提取数据,一个包含“用户”数据的文件和一个包含“任务”数据的文件。

'user.txt'
# username, password

admin, adm1n
king, king123
batman, batman123
superman, superman123
obiwan, obiwan123
anakin, anakin123
'tasks.txt'
# username, task title, task description, due date, date created, task completed

admin, Register Users, Use taskManager.py to add the usernames and passwords, 10 Oct 2019, 20 Oct 2019, Yes
admin, Assign initial tasks, Use taskManager.py to assign tasks, 10 Oct 2019, 25 Oct 2019, No
batman, Vengeance, Find a way to kill Superman, 12 Dec 2022, 28 Nov 2022, Yes
superman, Survival, Survive Batmans attempt to kill you, 25 Dec 2022, 12 Dec 2022, No
anakin, Vengeance, Embrace the dark side, 13 Mar 2025, 15 Dec 2022, Yes
testing, another test, test 2, 20 Dec 2021, 14 Dec 2022, No

I need to find the total number of tasks assigned to each user.我需要找到分配给每个用户的任务总数。 I have managed to read the 'user.txt' file and create a dictionary, but I can't figure out how to read through the 'tasks.txt' file and update the values for each of the keys.我已经设法读取“user.txt”文件并创建字典,但我无法弄清楚如何读取“tasks.txt”文件并更新每个键的值。

I have managed to extract user data from the 'user.txt' file to a list, and then create a dictionary.我已经设法将用户数据从“user.txt”文件中提取到一个列表中,然后创建一个字典。

# Empty list
total_users = []
# Read 'user.txt'
with open ("user.txt", "r", encoding = "utf-8") as f:
    # Total number of users
    for line in f:
        line = line.strip().split(", ")
        total_users.append(line[0])

# total users = ['admin', 'king', 'batman', 'superman', 'obiwan', 'anakin']

# Create empty dictionary with username keys
user_tasks = {}
for username in total_users:
    user_tasks.update({username:0})

# user_tasks = {'admin': 0, 'king': 0, 'batman': 0, 'superman': 0, 'obiwan': 0, 'anakin': 0}

I am struggling with how to read certain information from the 'tasks.txt' file and update the values in the dictionary.我正在努力研究如何从“tasks.txt”文件中读取某些信息并更新字典中的值。

I think the pseudocode would be something like this:我认为伪代码应该是这样的:

for key in user_tasks:
    with open ("tasks.txt", "r", encoding = "utf-8") as f:
        for line in f:
            line_items = re.split(r', |\n', line)
            if line_items[0] == key:
                update key value + 1

# Iterate for each key(user) in dictionary

Essentially, I'm breaking down each line into a list, and trying to use the list item to compare with the dictionary key.本质上,我将每一行分解成一个列表,并尝试使用列表项与字典键进行比较。

Ideally I would like to display the results in the following format:理想情况下,我想以以下格式显示结果:

Username:
Total tasks assigned to user:
Percentage of total number of tasks assigned to user:
Percentage of assigned tasks completed:
Percentage of assigned tasks to be completed:
Percentage of tasks assigned to be completed that are overdue:
--------------------------------------------------------------
# Iterate for each key(user) in dictionary

I think once I can figure out the total tasks assigned and how to use the dictionary to count, I think the rest should be quite similar.我想一旦我弄清楚分配的任务总数以及如何使用字典来计算,我认为其余的应该是非常相似的。

Any help with the first part would be greatly appreciated.对第一部分的任何帮助将不胜感激。

Thank you again:)再次感谢你:)

I thing if you first load all the data into a dictionary, it could be more easy make the statistics.我想如果你先将所有数据加载到字典中,那么进行统计可能会更容易。 This is a way to do that.这是一种方法。

data = {}
infoTitles = ['task title', 'task description', 'due date', 'date created', 'task completed'] 

# Load Data

# Create first each user as: {admin:'...','...'}
with open('user.txt','r') as usersFile:
    for line in usersFile.readlines():
        user,passw = [value.strip() for value in line.split(',')]
        data.setdefault(user,{'password':passw,'tasks':[]})

#In the dictionary, save the tasks as: tasks:{}
with open('tasks.txt','r') as tasksFile:
    lines = tasksFile.readlines()
    
    # This variable is for the statistics
    totalGlobalTasks = len(lines) 

    for line in lines:
        lineSplited = [value.strip() for value in line.split(',')]
        try:
            data[lineSplited[0]]['tasks'].append({infoTitles[ind]:value for ind,value in enumerate(lineSplited[1:])})
        except KeyError:
            print(f'Username not found: {lineSplited}')

The dictionary format is:字典格式为:

{'username':
    {
        'passw':'..',
        'tasks':[
            {
                'task title':'value',
                'task description':'value', 
                'due date':'value', 
                'date created':'value', 
                'task completed':'value'
            },'..'
        ]
        
    }
    
}

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

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