Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从Python列表中获取位置以生成动态范围_Python_List - Fatal编程技术网

从Python列表中获取位置以生成动态范围

从Python列表中获取位置以生成动态范围,python,list,Python,List,我有一个用Python构建的列表,使用以下代码: def return_hosts(): 'return a list of host names' with open('./tfhosts') as hosts: return [host.split()[1].strip() for host in hosts] tfhosts的格式是hosts文件的格式,所以我正在做的是将hostname部分填充到模板中,到目前为止这是可行的 我试图做的是确保即使添加了更多

我有一个用Python构建的列表,使用以下代码:

def return_hosts():
    'return a list of host names'
    with open('./tfhosts') as hosts:
        return [host.split()[1].strip() for host in hosts]
tfhosts的格式是hosts文件的格式,所以我正在做的是将hostname部分填充到模板中,到目前为止这是可行的

我试图做的是确保即使添加了更多主机,它们也会被放入默认部分,因为其他主机部分是固定的,但这部分我希望是动态的,为此我有以下几点:

rendered_inventory = inventory_template.render({
        'host_main': gethosts[0],
        'host_master1': gethosts[1],
        'host_master2': gethosts[2],
        'host_spring': gethosts[3],
        'host_default': gethosts[4:],
})
除了host_default部分下的最后一个主机之外,所有内容都被正确渲染,而不是得到一个换行分隔的主机列表,就像这样(这就是我想要的):

它只需在一个列表中写出剩余的主机名,如(我不想要):

我已尝试包装主机默认部分并将其拆分,但如果我尝试以下操作,则会出现运行时错误:

[gethosts[4:].split(",").strip()...

我相信
gethosts[4://code>返回一个列表,如果
gethosts
是一个列表(似乎是这样),那么它会直接将列表写入您的文件

另外,您不能在列表上执行
.split()
(我猜您希望在字符串上执行
.split
,但是
gethosts[4:][/code>返回一个列表)。我相信一个简单的方法是使用
str.join
\n
作为分隔符来连接列表中的字符串。范例-

rendered_inventory = inventory_template.render({
    'host_main': gethosts[0],
    'host_master1': gethosts[1],
    'host_master2': gethosts[2],
    'host_spring': gethosts[3],
    'host_default': '\n'.join(gethosts[4:]),
})
演示-

>>> lst = ['dc01-worker-02', 'dc01-worker-03']
>>> print('\n'.join(lst))
dc01-worker-02
dc01-worker-03


如果您拥有该模板,一种更简洁的方法是在
host\u default
的列表中循环,并打印模板中的每个元素。例如,您可以尝试使用。

什么是
inventory\u template.render()
函数?它使用的是Jinja,看起来是这样的:
inventory\u template=jinja2.template(inventory)rendered\u inventory=inventory\u template.render({'host\u main':gethosts[0],'host\u master1':gethosts[1],'host\u master2':gethosts[2],'host_spring':gethosts[3],'host_default':gethosts[4:],})
Brilliant,这正是我想要的。
rendered_inventory = inventory_template.render({
    'host_main': gethosts[0],
    'host_master1': gethosts[1],
    'host_master2': gethosts[2],
    'host_spring': gethosts[3],
    'host_default': '\n'.join(gethosts[4:]),
})
>>> lst = ['dc01-worker-02', 'dc01-worker-03']
>>> print('\n'.join(lst))
dc01-worker-02
dc01-worker-03