Найти и заменить подсписок в Python - PullRequest
0 голосов
/ 19 февраля 2020

Я довольно новичок в Python и программировании в целом и столкнулся с ситуацией, которую я не могу понять.

Я строю систему управления сотрудниками, в которую пользователь может добавлять нового сотрудника, просмотрите всех сотрудников, найдите сотрудника по 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 EMPLOYEES." To find an employee, type: "SEARCH EMPLOYEE BY SSN." 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':
        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 == "SEARCH":
        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[0], '-----------------\n')
                print('SSN:', employee[1], '\n')
                print('Phone:', '(' + employee[2][0] + employee[2][1] + employee[2][2] + ')' + employee[2][3] + employee[2][4] + employee[2][
                5] + '-' + employee[2][6] + employee[2][7] + employee[2][8] + employee[2][9], '\n') 
                print('Email:', employee[3], '\n')
                print('Salary:', '$' + str(employee[4]), '\n')
                print('            ----------------------------------------------------')
                found = True

        if found == False:
            print("Employee not found!")
    elif add_new == "CHANGE":
        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:
                changeName = input(employee.replace(employee[0], 'Please enter new name.\n'))
                changeSSN = input(employee.replace(employee[1], 'Please enter new SSN.\n'))
                changePhone = input(employee.replace(employee[2], 'Please enter new phone number.\n'))
                changeEmail = input(employee.replace(employee[3], 'Please enter new email.\n'))
                changeSalary = input(employee.replace(employee[4], 'Please enter new salary.\n'))

                found = True

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

Traceback (most recent call last):
  File "C:\Users\jmcra\Desktop\CPT200\Employment Management System - Functionality (4).py", line 54, in <module>
    changeName = input(employee.replace(employee[0], 'Please enter new name.\n'))
AttributeError: 'list' object has no attribute 'replace'

1 Ответ

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

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

employee[0] = input('New name')

вот ваш код

elif add_new == "CHANGE":
    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:
            changeName = input('Please enter new name.\n')
            changeSSN = input('Please enter new SSN.\n')
            changePhone = input('Please enter new phone number.\n')
            changeEmail = input('Please enter new email.\n')
            changeSalary = input('Please enter new salary.\n')

            employee[0] = changeName;
            employee[1] = changeSSN;
            employee[2] = changePhone;
            employee[3] = changeEmail;
            employee[4] = changeSalary;


            found = True

Вы можете просмотреть все методы списка здесь: https://www.programiz.com/python-programming/methods/list

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...