You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  1. Define the Shorthand Mapping: Create a dictionary that links each shorthand code to its full, human-readable label.
  2. 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.
  3. 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, so split() works correctly.
  • Safety Checks: We first check if ligne is not empty and if the first element exists in our mapping—this avoids IndexError (if a line is blank) and KeyError (if a shorthand isn't in our dict).
  • List Concatenation: [label_mapping[ligne[0]]] + ligne takes 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 10:03:03