如何将两个列表组合在一起? [英] How to combine two lists together?

查看:255
本文介绍了如何将两个列表组合在一起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表:

the_list:
  - { name: foo }
  - { name: bar }
  - { name: baz }

我使用了一个任务,该任务为其每个元素都获得了一些价值:

and I use a task which gets some value for its every element:

- name: Get values
  shell:
    magic_command {{ item.name }}
  with_items: the_list
  register: spells

从现在开始,我可以一起使用the_list及其对应的值:

from now on I can use the_list and its correspondig values together:

- name: Use both
  shell:
    do_something {{ item.0.name }} {{ item.1.stdout }}
  with_together:
    - "{{ the_list }}"
    - "{{ spells.results }}"

一切正常,但对于许多任务使用with_together感到不舒服,以后很难阅读该代码,因此我很乐意根据我可以在其中使用的内容来构建merged_list简单的方法.让我们说这样的话:

All works fine but it's uncomfortable to use with_together for many tasks and it'll be hard to read that code in a future so I would be more than happy to build merged_list from that which I can use in a simple way. Let say something like this:

merged_list:
 - { name: foo, value: jigsaw }
 - { name: bar, value: crossword }
 - { name: baz, value: monkey }

这令人困惑.任何人都可以帮忙吗?

which makes the puzzle. Anyone can help ?

推荐答案

这可能是一个矫kill过正的方法,但是您应该尝试编写自定义的过滤器插件.

It may be an overkill but you should try to write a custom filter plugin.

每次迭代the_list时,您都想将value添加到dict {name: 'foo'}上,对吗?

Each time you iterates the_list you simple wants to add value to that dict {name: 'foo'} right?

更新后,您只希望新字典具有如下值:{name: 'foo', value: 'jigsaw'}

After the update you just want that the new dict has the value like: {name: 'foo', value: 'jigsaw'}

该过滤器插件非常简单:

The filter plugin for that it's pretty simple:

def foo(my_list, spells):
    try:
        aux = my_list

        for i in xrange(len(aux)):
            my_list[i].update(spells[i])

        return my_list

    except Exception, e:
        raise errors.AnsibleFilterError('Foo plugin error: %s, arguments=%s' % str(e), (my_list,spells) )

class FilterModule(object):

    def filters(self):
       return {
            'foo' : foo
       }

在您的插件目录中添加python代码之后,您可以通过参数spells列表轻松调用foo插件:

After adding this python code inside your plugins directory, you can easily call the foo plugin passing the spells list as a parameter:

 - name: Get values
    shell:
      magic_command {{ item.name }}
    with_items: the_list
    register: spells

  - name: Use both
    shell:
      do_something {{ item.name }} {{ item.value }}
    with_items:
      - "{{ the_list | foo(spells.results) }}"

注意:python代码只是一个例子.阅读有关开发过滤器插件的Ansible文档.

NOTE: The python code it's just an example. Read the ansible documentations about developing filter plugins.

这篇关于如何将两个列表组合在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆