如何在Python中通过用户输入打印列表的指定部分
Python: Search Employee List and Print Formatted Details
Hey there! Let's work through this problem together. You've got a list of employee records stored as tuples, and you need to let users search by name to retrieve and print specific details in a structured format. Here's a straightforward solution:
Step 1: Full Working Code
# Define the employee list as provided employee_list = [ ('Jeffery Medina','Officer','1254','101442.00','23'), ('Katrina Peters','Officer','3423','94122.00','45'), ('Kim Alan','Captain','6434','101592.00','29'), ('Vincente Mendez','Officer','3235','110064.00','32'), ('Chris Boalen','Captain','8769','50436.00','56'), ('James Vito','Clerk','4451','23500.00','61'), ('Terry George','Fireman','3342','93354.00','32'), ('Zaid Dane','Officer','2345','84054.00','19'), ('Ernesto Rodriguez','Officer','9091','87006.00','35'), ('Josefine White','Fireman','3401','102228.00','26'), ('Mario Infante','Officer','3234','84054.00','22'), ('Juan Almonte','Fireman','4103','91272.00','50'), ('Kevin Smith','Fireman','3450','111492.00','62'), ('Abdum Smith','Captain','2234','95484.00','20'), ('Juan Gomez','Clerk','9023','23890.00','49') ] # Get user input for the employee name target_name = input("Who are you looking for? :") # Search through the list for a matching employee employee_found = False for emp in employee_list: # Match names case-insensitively so inputs like "jeffery medina" work if emp[0].lower() == target_name.lower(): # Print the details in your required format print(f"Employee Name: {emp[0]} Salary: {emp[3]} Age: {emp[4]}") employee_found = True break # Exit loop once we find the matching employee (assuming unique names) # Handle case where no matching employee is found if not employee_found: print(f"Sorry, we couldn't find an employee named '{target_name}'.")
Key Details Explained
- Case-Insensitive Matching: Using
.lower()on both the stored name and user input ensures the search works regardless of capitalization (e.g., "Katrina peters" will still find Katrina Peters). - Tuple Indexing: Each employee tuple has the structure
(Name, Position, ID, Salary, Age), so we use indexes 0, 3, and 4 to pull the required data. - Error Handling: The
employee_foundflag lets us give a clear message if the user searches for a name that doesn't exist in the list.
内容的提问来源于stack exchange,提问作者i don't know what im doing
相关产品推荐
相关产品推荐

