首页 > 解决方案 > 如何打印键列表的“键”值:值对?

问题描述

我有一个键:值对列表。如何分别打印它们中的每一个?

NetworkCommands = [
    (target + '/network/vlan'              , {"vlan": 30, "tagged_ports": [1,2], "ip": "172.0.10.1/16"}),
    (target + '/network/vlan'              , {"vlan": 51, "tagged_ports": [1,2], "ip": "10.0.0.1/16"}),
    (target + '/network/apply'             , {}),
    (target + '/network/sr/routing/static' , {"vlan": 51, "dest_ip": "100.0.0.0/8", "gateway": "10.0.0.2"}),
    (target + '/network/apply'             , {}),
]

这将打印两个:

for i in NetworkCommands:
    print(i)

('https://sonia:443/network/vlan', {'ip': '172.0.10.1/16', 'vlan': 30, 'tagged_ports': [1, 2]})
('https://sonia:443/network/vlan', {'ip': '10.0.0.1/16', 'vlan': 51, 'tagged_ports': [1, 2]})
('https://sonia:443/network/apply', {})
('https://sonia:443/network/sr/routing/static', {'vlan': 51, 'gateway': '10.0.0.2', 'dest_ip': '100.0.0.0/8'})
('https://sonia:443/network/apply', {})

标签: pythonlist

解决方案


您可以使用参数解包将每个元组中的两个元素中的每一个分配给它们自己的变量。

for first, second in NetworkCommands:
    print('The first element is', first)
    print('The second element is ', second)

或者,只需根据需要索引元组。

for i in NetworkCommands:
    print('The first element is', i[0])
    print('The second element is', i[1])

推荐阅读