AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79562876
Accepted
zagpoint
zagpoint
Asked: 2025-04-09 03:07:32 +0800 CST2025-04-09 03:07:32 +0800 CST 2025-04-09 03:07:32 +0800 CST

如何按列表成员的属性进行版本排序

  • 772

我正在尝试按照以下代码示例中的“名称”字段正确排序列表:

---
  - hosts: localhost
    vars:
      hosts:
        - name: host2
          uptime: 1d
        - name: host10
          uptime: 45d
        - name: host1
          uptime: 3m

    tasks:
    - name: version sort host list
      debug:
        #var: hosts | community.general.version_sort
        #var: hosts | dictsort(false, 'value')
        var: hosts | sort(attribute='name')

如您所见,它没有正确排序主机名(host2 应该排在 host10 之前)。我查了一下 version_sort 过滤器,但它不支持按属性排序。我知道如果主机名正确填充,就不会出现这种情况。但事实就是如此。我搜索了一下,没有看到有人问这个问题。还有其他建议吗?

TASK [version sort host list] *************************************
ok: [localhost] => {
    "hosts | sort(attribute='name')": [
        {
            "name": "host1",
            "uptime": "3m"
        },
        {
            "name": "host10",  <-------
            "uptime": "45d"
        },
        {
            "name": "host2",
            "uptime": "1d"
        }
    ]
}

概括:

感谢@Vladimir Botka提供的所有选项!我整合了第三个选项,并制定了以下方案。注意,我更新了字典列表,使其在使用fqdn时稍微复杂一些。但这个方案确实有效:

- hosts: localhost

  vars:
    hosts:
      - {name: host2.example.com, uptime: 1d}
      - {name: host10.example.com, uptime: 45d}
      - {name: host1.example.com, uptime: 3m}
      - {name: host3.example.com, uptime: 3m}
      - {name: host15.example.com, uptime: 45d}
      - {name: host20.example.com, uptime: 45d}
  tasks:
#    - debug:
#        msg: 
#        - "index: {{ hosts | map(attribute='name') | community.general.version_sort }}"
#        - "host_indexed: {{ dict(hosts|json_query('[].[name,@]')) }}"
#        - "solution: {{ (hosts | map(attribute='name') | community.general.version_sort) | map('extract', dict(hosts|json_query('[].[name,@]'))) }}"
    - debug: 
        var: (hosts | map(attribute='name') | community.general.version_sort) | map('extract', dict(hosts|json_query('[].[name,@]'))) 

结果如下:

PLAY [localhost] *****************************************************************************************************************************************
    
TASK [Gathering Facts] ***********************************************************************************************************************************
ok: [localhost]
    
TASK [debug] *********************************************************************************************************************************************
[WARNING]: Collection community.general does not support Ansible version 2.14.17
ok: [localhost] => {
    "(hosts | map(attribute='name') | community.general.version_sort) | map('extract', dict(hosts|json_query('[].[name,@]')))": [
        {
            "name": "host1.example.com",
            "uptime": "3m"
        },
        {
            "name": "host2.example.com",
            "uptime": "1d"
        },
        {
            "name": "host3.example.com",
            "uptime": "3m"
        },
        {
            "name": "host10.example.com",
            "uptime": "45d"
        },
        {
            "name": "host15.example.com",
            "uptime": "45d"
        },
        {
            "name": "host20.example.com",
            "uptime": "45d"
        }
    ]
}
    
PLAY RECAP ***********************************************************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
ansible
  • 1 1 个回答
  • 50 Views

1 个回答

  • Voted
  1. Best Answer
    Vladimir Botka
    2025-04-09T06:12:17+08:002025-04-09T06:12:17+08:00

    还有更多选项:

    1. 创建索引。下面的声明会从字符串中删除“host”。请根据您的需求进行调整
      index: "{{ hosts | map(attribute='name')
                       | map('regex_replace', 'host', '')
                       | map('int') }}"
    

    给出

      index: [2, 10, 1]
    

    注意:对于更复杂的模式,请使用 Python 正则表达式。例如,下面的声明给出相同的结果

      regex: '^\D*(\d+)$'
      replace: '\1'
      index: "{{ hosts | map(attribute='name')
                       | map('regex_replace', regex, replace)
                       | map('int') }}"
    

    合并索引

      hosts_indexed: "{{ index | map('community.general.dict_kv', 'index')
                               | zip(hosts)
                               | map('flatten')
                               | map('combine') }}"
    

    给出

      hosts_indexed:
          - {index: 2, name: host2, uptime: 1d}
          - {index: 10, name: host10, uptime: 45d}
          - {index: 1, name: host1, uptime: 3m}
    

    现在,对列表进行排序

      result: "{{ hosts_indexed | sort(attribute='index') }}"
    

    给出

      result:
          - {index: 1, name: host1, uptime: 3m}
          - {index: 2, name: host2, uptime: 1d}
          - {index: 10, name: host10, uptime: 45d}
    

    完整测试剧本示例

    - hosts: localhost
    
      vars:
    
        hosts:
          - {name: host2, uptime: 1d}
          - {name: host10, uptime: 45d}
          - {name: host1, uptime: 3m}
    
        index: "{{ hosts | map(attribute='name')
                         | map('regex_replace', 'host', '')
                         | map('int') }}"
        hosts_indexed: "{{ index | map('community.general.dict_kv', 'index')
                                 | zip(hosts)
                                 | map('flatten')
                                 | map('combine') }}"
        result: "{{ hosts_indexed | sort(attribute='index') }}"
    
      tasks:
    
        - debug:
            var: index | to_yaml
    
        - debug:
            var: hosts_indexed | to_yaml
    
        - debug:
            var: result | to_yaml
    

    1. 从索引创建字典
      hosts_indexed: "{{ dict(index | zip(hosts)) }}"
    

    给出

      hosts_indexed:
        1: {name: host1, uptime: 3m}
        2: {name: host2, uptime: 1d}
        10: {name: host10, uptime: 45d}
    

    现在,对字典进行排序

      result: "{{ hosts_indexed | dict2items
                                | sort(attribute='key')
                                | map(attribute='value') }}"
    

    给出相同的结果,但没有属性“索引”

      result:
        - {name: host1, uptime: 3m}
        - {name: host2, uptime: 1d}
        - {name: host10, uptime: 45d}
    

    完整测试剧本示例

    - hosts: localhost
    
      vars:
    
        hosts:
          - {name: host2, uptime: 1d}
          - {name: host10, uptime: 45d}
          - {name: host1, uptime: 3m}
    
        index: "{{ hosts | map(attribute='name')
                         | map('regex_replace', 'host', '')
                         | map('int') }}"
        hosts_indexed: "{{ dict(index | zip(hosts)) }}"
        result: "{{ hosts_indexed | dict2items
                                  | sort(attribute='key')
                                  | map(attribute='value') }}"
    
      tasks:
    
        - debug:
            var: index | to_yaml
    
        - debug:
            var: hosts_indexed | to_yaml
    
        - debug:
            var: result | to_yaml
    

    1. 创建自定义过滤器。例如,
    shell> cat filter_plugins/my_sort.py 
    from distutils.version import LooseVersion
    
    
    def my_sort(l):
        return sorted(l, key=LooseVersion)
    
    
    class FilterModule(object):
        def filters(self):
            return {
                'my_sort': my_sort,
                }
    

    用它来对名称进行排序

      index: "{{ hosts | map(attribute='name') | my_sort }}"
    

    给出

      index: [host1, host2, host10]
    

    使用属性“name”作为键

      hosts_indexed: "{{ dict(hosts | json_query('[].[name, @]')) }}"
    

    给出

      hosts_indexed:
        host1: {name: host1, uptime: 3m}
        host10: {name: host10, uptime: 45d}
        host2: {name: host2, uptime: 1d}
    

    现在,使用列表“索引”来提取排序列表

      result: "{{ index | map('extract', hosts_indexed) }}"
    

    给出

      result:
        - {name: host1, uptime: 3m}
        - {name: host2, uptime: 1d}
        - {name: host10, uptime: 45d
    

    完整测试剧本示例

    - hosts: localhost
    
      vars:
    
        hosts:
          - {name: host2, uptime: 1d}
          - {name: host10, uptime: 45d}
          - {name: host1, uptime: 3m}
    
        index: "{{ hosts | map(attribute='name') | my_sort }}"
        hosts_indexed: "{{ dict(hosts | json_query('[].[name, @]')) }}"
        result: "{{ index | map('extract', hosts_indexed) }}"
    
      tasks:
    
        - debug:
            var: index | to_yaml
    
        - debug:
            var: hosts_indexed | to_yaml
    
        - debug:
            var: result | to_yaml
    
    • 3

相关问题

  • 如何从组中的所有主机中提取多个主机变量?

  • 仅在本地主机上运行一次 ansible 任务

  • 如何在 Ansible 循环中注册变量?

  • Ansible 中是否可以使用寄存器动态分配文件源?[关闭]

  • 通过 Ansible map('regex_replace') 后比较两个列表

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve