Python嵌套列表添加索引及按finishTime字段排序问题咨询
Got it, let's sort this out for you! The core issue here is that you're likely storing all an athlete's details as a single unstructured entry in your datasets array—like a combined string or non-keyed value—so you can't easily extract the finishTime to use it for sorting.
The simple fix is to store each athlete's data as a dictionary, where every piece of information (gender, name, finish time, lane number) gets its own explicit key. This way, finish_time becomes a separate, accessible value we can target for sorting operations.
Here's the adjusted code with this approach:
import time datasets = [] for i in range(1, 3): print("Inputting Data for Lane", i) gender = input("Is the athlete male or female? ") athlete_name = input("What is the athlete's name? ") # Capture finish time as a numeric value (float works for seconds with decimals) finish_time = float(input("What is the athlete's finish time (in seconds)? ")) # Package all data into a dictionary with clear, named keys athlete_entry = { "lane": i, "gender": gender, "name": athlete_name, "finish_time": finish_time } datasets.append(athlete_entry) # Sort the dataset by finish_time (ascending order = fastest first) sorted_results = sorted(datasets, key=lambda entry: entry["finish_time"]) # Optional: Print sorted results to verify print("\n=== Sorted Race Results (Fastest to Slowest) ===") for rank, athlete in enumerate(sorted_results, 1): print(f"{rank}. {athlete['name']} (Lane {athlete['lane']}) - {athlete['finish_time']} seconds")
Key Changes Explained:
- Dictionary Structure: Each athlete's data is now stored as a dictionary with distinct keys (
lane,gender,name,finish_time), so no more lumping everything into a single array index. - Sorting with
sorted(): Thekeyparameter uses a lambda function to grab thefinish_timevalue from each dictionary, which tells Python exactly what to sort by. If you want slowest-to-fastest order, just addreverse=Trueinside thesorted()call. - Numeric Finish Time: We convert the input finish time to a
floatso Python can properly compare numeric values (instead of treating them as strings, which would sort incorrectly).
This structured approach not only fixes your sorting problem but also makes it way easier to filter, edit, or display the race data later on—perfect for your athlete entry form!
内容的提问来源于stack exchange,提问作者Mohamed Ismail

