You need to enable JavaScript to run this app. 创建值为列表的字典列表:从文本转储提取设备数据构造目标结构
优惠活动
大模型
产品
解决方案
定价
更多

创建值为列表的字典列表:从文本转储提取设备数据构造目标结构

问题分析

你当前的代码存在两个核心问题:

  • 用列表存储单键字典的结构不符合需求,你预期的带键值对的[]写法在Python中不合法,应该用字典存储设备到数值列表的映射
  • 每次读取到数值都会新建字典追加到列表,没有将同一个设备的数值合并到同一个列表中,同时读取到的数值是字符串类型,无法直接用于统计计算
代码修改方案

你可以直接替换为以下修改后的代码:

import re

# 把原来的列表改为字典,存储结构为 {设备号: [数值列表]}
r1_dict = {}
r2_dict = {}

current_device = None
device_type = None

def match_device(line):
    # 同时匹配r1/r2和设备号,减少重复代码
    matched = re.match(r'^(r[12])\s(r\d+)$', line.strip())
    if matched:
        return matched.group(1), matched.group(2)
    return None, None

def match_reading(line):
    matched = re.match(r'^(\d+)\s(\d+\.\d+)$', line.strip())
    if matched:
        # 直接返回float类型的数值,方便后续计算
        return float(matched.group(2))
    return None

with open("data.txt") as f:
    for line in f:
        line = line.strip()
        if not line:
            continue
        dev_type, dev_id = match_device(line)
        if dev_type:
            current_device = dev_id
            device_type = dev_type
            continue
        
        reading = match_reading(line)
        if reading and current_device and device_type:
            # 把数值加到对应设备的列表里
            if device_type == 'r1':
                if current_device not in r1_dict:
                    r1_dict[current_device] = []
                r1_dict[current_device].append(reading)
            elif device_type == 'r2':
                if current_device not in r2_dict:
                    r2_dict[current_device] = []
                r2_dict[current_device].append(reading)

print("r1_dict =", r1_dict)
print("r2_dict =", r2_dict)
运行输出
r1_dict = {'r01': [77.7, 76.0, 77.7], 'r04': [74.6, 75.6, 75.8]}
r2_dict = {'r02': [74.7, 74.0, 76.7], 'r03': [74.2, 74.1, 76.8]}

该结构完全支持你后续遍历计算均值等统计指标,比如计算r01的均值可以直接用sum(r1_dict['r01'])/len(r1_dict['r01'])。

内容的提问来源于stack exchange,提问作者B Mandrake

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 09:45:01