Есть ли способ найти строку в списке и распечатать только элемент списка, связанный с этой строкой? - PullRequest
0 голосов
/ 18 февраля 2020

Я работаю в системе управления сотрудниками и хотел бы, чтобы мой пользователь искал сотрудника по SSN. Когда сотрудник будет найден, я хочу напечатать список, связанный с этим SSN. В конце концов, я хотел бы найти сотрудника по SSN и позволить пользователю также редактировать данные в полях. Сейчас я не могу понять, как связать поиск SSN со списком. Я могу найти SSN, но не знаю, как его отобразить. Как мне это сделать?

employee_info = [ ]

while True: # While loop created to make the script constantly run
    counter = len(employee_info) # Counter created so that the user will know how many entries there are

    print('There are', '(', (int(counter)), ')', 'employees in the system.\n')

    add_new = input('Would you like to add a new employee to the system, find an employee\'s record by SSN, change an employee\'s information or view all employee entries in the system?\
    To add an employee, type: "ADD". To view all employees currently in the system, type: "VIEW ALL." To find an employee, type: "FIND." To change employee info, type: "CHANGE."\n'\
    ) #Added option to add an employee, find an employee by SSN, change information or to view all employees currently the system

    if add_new == 'ADD':
        while True: # Loop created to input employees with option to quit
            employee_index = [input('Employee Name\n'), input('Employee SSN\n'), \
            input('Employee Telephone Number ***Entered as (555)555-5555*** \n'), input('Employee Email\n'), input('Employee Salary ***Entered as $xxxx***\n')] 
            employee_info.append(employee_index)
            more_employees = input('Would you like to add another employee? Y or N.\n')
            if more_employees == 'Y':
                continue
            elif more_employees == 'N':
                break

    elif add_new == 'VIEW ALL':
        for employee_index in employee_info:
            print('            -----------------', employee_index[0], '-----------------\n')
            print('SSN:', employee_index[1], '\n')
            print('Phone:', '(' + employee_index[2][0] + employee_index[2][1] + employee_index[2][2] + ')' + employee_index[2][3] + employee_index[2][4] + employee_index[2][
            5] + '-' + employee_index[2][6] + employee_index[2][7] + employee_index[2][8] + employee_index[2][9], '\n') 
            print('Email:', employee_index[3], '\n')
            print('Salary:', '$' + str(employee_index[4]), '\n')
            print('            ----------------------------------------------------')

    elif add_new == "FIND":
        find_emp = input('Please enter the employee SSN in the following format: 333221111.\n')
        if find_emp in employee_index:

Ответы [ 3 ]

0 голосов
/ 18 февраля 2020

Вы можете проанализировать каждого сотрудника в списке, и если employee[1] == find_emp, т. Е. Если серийный номер совпадает, вы можете распечатать данные сотрудника.

elif add_new == "FIND":
    find_emp = input('Please enter the employee SSN in the following format: 333221111.\n')
    found = False
    for employee in employee_info:
        if employee[1] == find_emp:
            print('            -----------------', employee_index[0], '-----------------\n')
            print('SSN:', employee_index[1], '\n')
            print('Phone:', '(' + employee_index[2][0] + employee_index[2][1] + employee_index[2][2] + ')' + employee_index[2][3] + employee_index[2][4] + employee_index[2][
            5] + '-' + employee_index[2][6] + employee_index[2][7] + employee_index[2][8] + employee_index[2][9], '\n') 
            print('Email:', employee_index[3], '\n')
            print('Salary:', '$' + str(employee_index[4]), '\n')
            print('            ----------------------------------------------------')
            found = True

    if found == False:
        print("Employee not found!")

Если сотрудник не найден, вы печатаете соответствующее сообщение об ошибке.

0 голосов
/ 18 февраля 2020

Похоже, вы читаете в списке индексов сотрудников, и каждый индекс сотрудников представляет собой список из пяти элементов, второй из пяти - SSN. Таким образом, вы можете просмотреть список из 5 пунктов, проверив 2-й из 5-ти на соответствие SSN. Итак ...

def match_the_ssn(list_of_lists, ssn):
    for item in list_of_lists:
        try:
            if item[1] == ssn:
                print(item)
                return item
        except:
            pass
    return

Что-то вроде этих строк ... Пробежитесь по списку, просматривая каждый подсписок. Для каждого подсписка проверьте, является ли подсписок [1] ​​тем ssn, который вы хотите. Если это так, у вас есть подсписок, чтобы сделать то, что вы хотите.

0 голосов
/ 18 февраля 2020

Вместо того, чтобы диктовать, попробуйте использовать такие пары ключей, как это

mydict = {"SSN": 465736283, "Name": 'Some Dude'}

Но имейте это так

{
    "employee": {
        "SSN": "1574083",
        "username": "gustog",
        "full_name": "Don Won",
        "profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_1574083_75sq_1295469061.jpg",
        "bio": "This is my bio",
        "website": "http://donwon.gov",
        "counts": {
            "media": 1320,
            "follows": 420,
            "followed_by": 3410
        }
}

Это может позволить вам лучше хранить информацию, а затем быстрее ее извлекать вместо зацикливания на массиве

...