Python新手求助:根据字典映射为列表添加对应前缀元素
Solution for Prepending Full-Label Prefixes to Your List
Hey there! Let's work through this problem together. Your goal is to take a list like ['DR', '0.8282312925170068'] and turn it into ['DETECTION RATE', 'DR', '0.8282312925170068'] by mapping shorthand codes (DR, FAR, FNR) to their full names.
First, let's fix the issue with your original code: you can't put assignment statements (like ligne = ["Detection Rate"] + ligne) as values in a dictionary—Python will throw a syntax error here. Instead, we'll use a mapping dictionary to store the shorthand-to-full-name pairs, then use that to build your modified list.
Step-by-Step Solution
- Define the Shorthand Mapping: Create a dictionary that links each shorthand code to its full, human-readable label.
- Process Each Line Safely: Read your file line by line, split each line into a list, then check if the first element matches a key in our mapping.
- Build the Modified List: If there's a matching key, prepend the full label to your original list.
Working Code Example
# Define our shorthand to full-label mapping label_mapping = { "DR": "DETECTION RATE", "FAR": "FALSE ALARM RATE", "FNR": "FALSE NEGATIVE RATE" # Fill in the correct full name here if needed } # Use a context manager to safely read the file (auto-closes when done) with open("your_file.txt", "r") as f: for line in f.readlines(): # Strip extra whitespace/newlines and split into a list ligne = line.strip().split() # Only modify the list if it's not empty and the first element is in our mapping if ligne and ligne[0] in label_mapping: # Prepend the full label to the original list ligne = [label_mapping[ligne[0]]] + ligne # Do whatever you need with the modified ligne here (print, write to file, etc.) print(ligne)
Key Notes
strip(): This removes any leading/trailing whitespace (like newlines) from the line, sosplit()works correctly.- Safety Checks: We first check if
ligneis not empty and if the first element exists in our mapping—this avoidsIndexError(if a line is blank) andKeyError(if a shorthand isn't in our dict). - List Concatenation:
[label_mapping[ligne[0]]] + lignetakes the full label (as a single-element list) and combines it with your original list, giving you the exact structure you want.
内容的提问来源于stack exchange,提问作者Greg Symsym
相关产品推荐
相关产品推荐

