如何规范化包含不相关条目的列表

How can I normalize a list that has entries which are not relevant

我正在从 K8 中提取信息并创建一个 json 文件。从该文件中,我提取了三个属性并创建了一个服务列表。

服务可能有多个版本不同的条目。我的目标是删除旧版本并仅保留最新版本。

class Service:
    def __init__(self, app, version, port):
        self.app = app
        self.version = version
        self.port = port

    def __str__(self):
        return 'service: {} version: {} port: {}'.format(
            self.app, self.version, self.port)

此函数处理文件:

def process_file(file):
    services = []
    with open(file, 'r') as handle:
        data = json.load(handle)
        for _, item in enumerate(data['items']):
            app = item['spec']['selector']['app'].lower()
            version = item['spec']['selector']['version']
            for protocol in item['spec']['ports']:
                if protocol['name'] == 'https':
                    port = protocol['nodePort']
                    services.append(Service(app, version, port))
        return services

和return以下信息:

service: accessoryservice version: 1.2.12 port: 31751
service: aktivateuserinterface version: 1.2.198 port: 30265
service: approvalservices version: 1.1.0 port: 30230
service: approvalservices version: 1.2.11 port: 31380
service: cachemanagement version: 1.0.0 port: 31805
service: cachemanagement version: 1.1.0 port: 32678
service: cachemanagement version: 1.2.8 port: 31799
service: cashdrawermgmt version: 1.1.0 port: 32576
service: cashdrawermgmt version: 1.2.4 port: 31905
service: clovertradeupservices version: 1.2.9 port: 30562
service: collateralservice version: 1.0.0 port: 32037
service: collateralservice version: 1.1.0 port: 32244
service: collateralservice version: 1.2.8 port: 31445
service: compatibilityservice version: 1.0.0 port: 31335
service: compatibilityservice version: 1.1.0 port: 32739
service: compatibilityservice version: 1.2.13 port: 32472
service: customerdetails version: 1.0.0 port: 31007
service: customerdetails version: 1.1.2 port: 30209
service: customerdetails version: 1.2.57 port: 30546

如何处理此信息并删除缓存管理 1.0.0 和 1.1.0?目标是每个服务都有一个版本,例如列表中的 cachemanagement 1.2.8。

使用字典而不是列表,您可以在添加之前检查版本是否更新。

from packaging.version import parse  # used to compare version strings

def process_file(file):
    services = {} # dict
    with open(file, 'r') as handle:
        data = json.load(handle)
        for _, item in enumerate(data['items']):
            app = item['spec']['selector']['app'].lower()
            version = item['spec']['selector']['version']
            for protocol in item['spec']['ports']:
                if protocol['name'] == 'https':
                    port = protocol['nodePort']
                    if app not in services:
                      services[app] = Service(app, version, port)
                    elif parse(services[app].version) < parse(version):  # update service only if version newer
                      services[app] = Service(app, version, port)
        return services