【问题标题】:From YAML, list indices must be integers or slices, not str在 YAML 中,列表索引必须是整数或切片,而不是 str
【发布时间】:2018-08-30 11:45:05
【问题描述】:

我正在尝试将一些变量从 YAML 文件传递​​到 python 脚本。 我的 YAML 文件是一个嵌套字典,其中包含一个列表作为特定键的值

---
source:
  address:
    - 10.0.0.1
    - 10.0.0.2
    - 172.16.0.1
  mask:
    - 255.255.255.255
    - 255.255.255.255
    - 255.255.255.0

我正在尝试遍历列表并打印列表的每个值

#!/usr/bin/env python3
import yaml, sys

inventory = yaml.load(open(sys.argv[1], 'rb'))

def function():
    for i,j in ['source']['address'],['source']['mask']:
        if inventory['source']['mask'] == '255.255.255.255':
            print('object-group network H-{}-32'.format(i))

function()

但是我收到以下错误

TypeError: list indices must be integers or slices, not str

谢谢

【问题讨论】:

  • for i,j in ['source']['address'],['source']['mask'] 不是有效的 python...

标签: python python-3.x loops yaml


【解决方案1】:

['source']['address'] 尝试使用索引 'address' 索引单元素列表 ['source'],这对 Python 列表没有任何意义(因此会出现错误)。

你可能想要这样的东西:

#!/usr/bin/env python3
import yaml, sys

def function(inventory):
    source = inventory['source']
    for address, mask in zip(source['address'], source['mask']):
        if mask == '255.255.255.255':
            print('object-group network H-{}-32'.format(address))

inventory = yaml.load(open(sys.argv[1], 'rb'))
function(inventory)

【讨论】:

    猜你喜欢
    • 2016-05-25
    • 2017-10-09
    • 2015-12-09
    • 2021-09-01
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多