【问题标题】:Python selecting variables based inside functionPython选择基于内部函数的变量
【发布时间】:2022-11-02 23:55:40
【问题描述】:

我正在尝试创建可以从 API 库中提取信息的函数,但我很难弄清楚如何将变量选择传递给函数而不被读取为值。

代码示例:

def get_list(api, val = None):
    response =[]
    list = api
    for i in list:
        response.append(f'i.{val}')
    return (response)


devices = get_list(api.devices.all(), 'name')

print(devices )

给我一长串“i.name”

我需要解决我的名字作为变量选择而不是实际值

我累了:

response.append(vars()[f'i.{val}']) # locals(), globals()

但我收到错误:“KeyError:'i.name'”

我认为问题在于“i.name”并没有真正作为函数中的变量存在。

【问题讨论】:

  • 我试图确保我理解你想要什么。您试图在 val 函数参数中传递属性的名称并在 for 循环中获取该属性的值?
  • 我无法理解问题/问题,您可以尝试用更多代码和一些示例来解释它吗?即使有这条评论stackoverflow.com/a/74290027/13564014 我也无法理解它们之间的关系。

标签: python api


【解决方案1】:

当您使用设备调用此函数时,您将参数“名称”作为“val”传递,然后您将其循环并附加到结果中。

如果您还可以在此处包含您想要的结果,那将很有帮助,因为目前还不清楚。

【讨论】:

  • 当您在函数内部循环 list 时(这对于变量名来说不是一个好的选择,因为它会影响 Python 内置的 list 函数)您当前没有使用 i 作为您在 for 循环中声明的变量,而只是作为字符串值。如果你想使用你声明的i的实际值并且API值是一个字符串,你可以写response.append(f'{i}.{val}')。如果不是字符串,那么response.append(f'{str(i)}.{val}')
  • response.append(f'{i}.{val}') = TypeError: 'type' object is not iterable
  • response.append(f'{str(i)}.{val}') = TypeError: 'type' object is not iterable
【解决方案2】:

我正在使用 LibremsAPI 库从 LibreNMS 读取数据

常规 GET 请求如下所示:

ip_list []
for device in lnms.devices.all():
    ip_list.append(device.ip)

name_list []
for device in lnms.devices.all():
    ip_list.append(device.sysName)

因此,为了不必对我需要的 api 请求进行每一个变体,我们的想法是有一个“列表”函数。

【讨论】:

    【解决方案3】:

    据我了解,您想编写一个函数,这样您就不必重复for

    ip_list = []
    for device in lnms.devices.all():
        ip_list.append(device.ip)
    
    name_list = []
    for device in lnms.devices.all():
        ip_list.append(device.sysName)
    

    首先,在您的代码中,您使用 list 作为变量,您不应该导致 list 是一个内置关键字。

    This comment 解释了为什么您的代码不起作用

    这就是它的工作方式

    def get_data(devices, key):
        response = []
        for device in devices:
            response.append(device[key])
        return response
    

    甚至更短的使用list comprehension

    def get_data(devices, key):
        return [device[key] for device in devices]
    

    然后你可以做

    ip_list = []
    ip_list = get_data(lnms.devices.all(), 'ip')
    
    name_list = []
    name_list = get_data(lnms.devices.all(), 'sysName')
    

    如果你不想重复lnms.devices.all() 您可以编写如下函数

    def get_data_from_devices(key):
        response = []
        for device in lnms.devices.all():
            response.append(device[key])
        return response
    

    或者使用列表理解

    def get_data_from_devices(key):
        return [device[key] for device in lnms.devices.all()]
    

    然后你会称它们为

    ip_list = []
    ip_list = get_data_from_devices('ip')
    
    name_list = []
    name_list = get_data_from_devices('sysName')
    

    PS:需要更好的函数名称

    【讨论】:

    • 使用“response.append(device [key])”我得到:TypeError:'LibreNMSEndpoint'对象不可下标
    【解决方案4】:

    我是 Python 的新手,从上面的文字中可以看出我没有很好地解释自己,所以这是我试图让事情更清楚的尝试。

    命令“lnms_device_names = get_data(lnms.devices.all(), 'sysName')”

    原始尝试:

    
    
    def get_data(devices, key):
        response = []
        for device in devices:
            response.append(device.key)
        return response
    
    # => Endpoint devices/29/key does not exists
    
    def get_data(devices, key):
        response = []
        for device in devices:
            response.append(f'device.{key}')
        return response
    
    # => ['device.sysName', 'device.sysName', 'device.sysName', 'device.sysName']
    

    在此线程中使用建议失败的尝试:

    def get_data(devices, key):
        return [device[key] for device in devices]
    
    # => TypeError: 'LibreNMSEndpoint' object is not subscriptable
    
    def get_data(devices, key):
        response = []
        for device in devices:
            response.append(device[key])
        return response
    
    # => TypeError: 'LibreNMSEndpoint' object is not subscriptable
    
    def get_data(devices, key):
        response = []
        for device in devices:
            response.append(f'{device}.{key}') # same result with f'{str(device)}.{key}'
        return response
    
    # => full data dump no filtering by key
    

    不使用任何功能时的外观

    #WORKS:
    lnms_device_names = []
    for device in lnms.devices.all():
        lnms_device_names.append(device.sysName)
    
    # => ['dc2-h1-ipn03', 'dc2-h1-spine1', 'dc2-h1-spine2', 'dc2-h1-leaf1']
    

    数据结构:

    {
                "device_id": 1,
                "inserted": "2022-08-15 15:50:33",
                "hostname": "172.21.142.10",
                "sysName": "dc2-h1-ipn03",
                "display": null,
                "ip": "",
                "overwrite_ip": null,
                "community": "xxxxxxx",
                "authlevel": null,
                "authname": null,
                "authpass": null,
                "authalgo": null,
                "cryptopass": null,
                "cryptoalgo": null,
                "snmpver": "v2c",
                "port": 161,
                "transport": "udp",
                "timeout": null,
                "retries": null,
                "snmp_disable": 0,
                "bgpLocalAs": 1,
                "sysObjectID": ".1.3.6.1.4.1.9.12.3.1.3.1812",
                "sysDescr": "Cisco NX-OS(tm) nxos.7.0.3.I7.9.bin, Software (nxos), Version 7.0(3)I7(9), RELEASE SOFTWARE Copyright (c) 2002-2020 by Cisco Systems, Inc. Compiled 8/27/2020 4:00:00",
                "sysContact": null,
                "version": "7.0(3)I7(9)",
                "hardware": "N9K-C93180YC-EX",
                "features": null,
                "location_id": 1,
                "os": "nxos",
                "status": 1,
                "status_reason": "",
                "ignore": 0,
                "disabled": 0,
                "uptime": 47671869,
                "agent_uptime": 0,
                "last_polled": "2022-11-02 15:28:35",
                "last_poll_attempted": null,
                "last_polled_timetaken": 8.46,
                "last_discovered_timetaken": 293.18,
                "last_discovered": "2022-11-02 12:05:18",
                "last_ping": "2022-11-02 15:31:02",
                "last_ping_timetaken": 1.83,
                "purpose": null,
                "type": "network",
                "serial": "xxxxxx",
                "icon": "cisco.svg",
                "poller_group": 0,
                "override_sysLocation": 0,
                "notes": null,
                "port_association_mode": 1,
                "max_depth": 0,
                "disable_notify": 0,
                "dependency_parent_id": null,
                "dependency_parent_hostname": null,
                "location": "xxxxx",
                "lat": 64.132453,
                "lng": -21.877419
            },
            {
                "device_id": 2,
                ....
                ....
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-02
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多