【问题标题】:How to create a list dict dynamically with Python如何使用 Python 动态创建列表字典
【发布时间】:2021-04-02 06:35:46
【问题描述】:

我有这个输入要处理:

['', '', '', '', '  Huawei Integrated Access Software (MA5600T).', '  Copyright(C) Huawei Technologies Co., Ltd. 2002-2014. All rights reserved.', '', '  -----------------------------------------------------------------------------', '  User last login information:', '  -----------------------------------------------------------------------------', '  Access Type : Telnet ', '  IP-Address  : 1.1.1.1', '  Login  Time : 2020-12-24 11:51:33+01:00', '  Logout Time : 2020-12-24 11:51:38+01:00', '  -----------------------------------------------------------------------------', '', 'OLT-SALUZZO_01>enable', '', 'OLT-SALUZZO_01#display ont autofind all \x1b[1D\x1b[1C', '   ----------------------------------------------------------------------------', '   Number              : 1', '   F/S/P               : 0/17/7', '   Ont SN              : 485754437D85CA9E (HWTC-7D85CA9E)', '   Password            : 0x00000000000000000000', '   Loid                : ', '   Checkcode           : ', '   VendorID            : HWTC', '   Ont Version         : 159D.A', '   Ont SoftwareVersion : V5R019C00S100', '   Ont EquipmentID     : EG8145V5', '   Ont autofind time   : 2020-12-24 08:38:28+01:00', '   ----------------------------------------------------------------------------', '   Number              : 2', '   F/S/P               : 0/17/7', '   Ont SN              : 48575443A9517A9E (HWTC-A9517A9E)', '   Password            : 0x00000000000000000000', '   Loid                : ', '   Checkcode           : ', '   VendorID            : HWTC', '   Ont Version         : 159D.A', '   Ont SoftwareVersion : V5R019C00S100', '   Ont EquipmentID     : EG8145V5', "---- More ( Press 'Q' to break ) ----"]

我需要从中创建一个这样的输出:

[{'F/S/P': '0/17/7', 'SN': ' 485754437D85CA9E', 'Password': None}, {'F/S/P': '0/17/7', 'SN': '48575443A9517A9E ', 'Password': None}]

我的功能是这样的:

tn.write("display ont autofind all ".encode('utf-8') + b"\n")
return_lineid = tn.read_until('The number of GPON'.encode('utf-8'), 3).decode('utf-8')
data_return = return_lineid.splitlines()
autofind_list=[]
records = []
current_record = {}
for line in data_return:
    line = line.strip()
    if not line:  # empty line
        records.append(current_record)
        current_record = {}
    else:
        if "F/S/P" in line:
            key, value = line.split(':')
            key = key.strip()
            value = value.strip()
            current_record[key] = value
            print(current_record)
        if "Ont SN" in line:
            key, value = line.split(':')
            key = key.strip()
            value = value.strip()
            value = re.sub(r'\(.*\)', '', value)
            current_record[key] = value
            print(current_record)
        if "Password" in line:
            key, value = line.split(':')
            key = key.strip()
            value = value.strip()
            if value == '0x00000000000000000000':
                current_record[key]=None
            else:
                current_record[key] = value

        autofind_list.append(current_record.copy())

#for removing same records
seen = set()
new_l = []
for d in autofind_list:
    t = tuple(d.items())
    if t not in seen:
        seen.add(t)
        new_l.append(d)

print(new_l)

但它返回了这个,我几乎达到了我的目标:

[{}, {'F/S/P': '0/17/7'}, {'F/S/P': '0/17/7', 'Ont SN': '485754437D85CA9E '}, {'F/S/P': '0/17/7', 'Ont SN': '485754437D85CA9E ', 'Password': None}, {'F/S/P': '0/17/7', 'Ont SN': '48575443A9517A9E ', 'Password': None}]

但我想删除无用的对象,例如 {}, {'F/S/P': '0/17/7'}

有人可以帮我解决这个问题吗?或者能给我一个提示吗?

提前谢谢你

【问题讨论】:

  • “每次出现问题,例如这个”——该输出的具体问题是什么?请阅读How to Ask。让我们尽可能轻松地为您提供帮助。
  • (旁注:它们都不是 JSON,它只支持双引号字符串并使用 null,而不是 None。我怀疑你确实有包含字典的 Python 列表。)
  • 如果你阅读,每次输出都是一样的
  • 是的,我需要一个 json 或类似的东西,我想我的问题很清楚
  • “如果你阅读,每次输出都是一样的”——所以你希望我们注意到“485754437D85CA9E”和“48575443A9517A9E”之间的区别,隐藏在我们需要横向滚动的长输出中阅读? 再次,请阅读How to Ask,特别注意“假装您正在与一位忙碌的同事交谈”的建议。这些值的差异应在您的问题中明确指出。理想情况下,您会提供minimal reproducible example。这里有很多代码只会分散注意力。

标签: python telnetlib


【解决方案1】:

我不确定您对此autofind_list 的计划是什么,但我认为这是您尝试解决在records 中没有出现一条记录的问题。这可以通过在循环完成后简单地添加current_record 来解决。

那么唯一的问题是第一个空记录,因为在开头有一个不必要的空行。这可以通过在将 current_record 添加到 records 之前简单地检查是否已填充来完成(如果两个空行在一行中,这也可以防止出现问题)。

这里是完整的代码:

records = []
current_record = {}
for line in data_return:
    line = line.strip()
    if not line:  # empty line
        if current_record: # no data recorded
            records.append(current_record)
            current_record = {}
    else:
        if "F/S/P" in line:
            key, value = line.split(':')
            key = key.strip()
            value = value.strip()
            current_record[key] = value
        if "Ont SN" in line:
            key, value = line.split(':')
            key = key.strip()
            value = value.strip()
            value = re.sub(r'\(.*\)', '', value)
            current_record[key] = value
        if "Password" in line:
            key, value = line.split(':')
            key = key.strip()
            value = value.strip()
            if value == '0x00000000000000000000':
                current_record[key] = None
            else:
                current_record[key] = value

if current_record:
    records.append(current_record)

records 现在包含我认为您想要的列表。


由于您在帖子中的示例数据实际上并不代表您给出的输入,其中记录由---- 仅破折号线分隔,您需要将if not line: 替换为if not line or set(line) == {'-'}:

【讨论】:

  • 它只返回一条记录:[{'F/S/P': '0/17/7', 'Ont SN': '48575443A9517A9E', 'Password': None}]
  • @snuz 它不适合我。你能举个例子输入吗?通过 pastebin?
  • 问题中都描述了,我需要处理的输入是我在问题中写的第一件事
  • @snuz 这个输入对我有用。你确定你有我答案的最后几行吗?
  • 是的。我确定!如果我打印 'records' 它只打印 '[{'F/S/P': '0/17/7', 'Ont SN': '48575443A9517A9E', 'Password': None}]'
猜你喜欢
  • 1970-01-01
  • 2018-09-17
  • 2016-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-18
  • 2018-05-18
  • 2021-06-16
相关资源
最近更新 更多