python - 如何打印键列表的“键”值:值对?
问题描述
我有一个键:值对列表。如何分别打印它们中的每一个?
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', {})
解决方案
您可以使用参数解包将每个元组中的两个元素中的每一个分配给它们自己的变量。
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])
推荐阅读
- nativescript - 是否可以在 nativescript 中为进度元素添加最小限制
- javascript - 将 NODE_ENV 传递给 Windows 10 的 npm 脚本
- swift - 为我们的 Swift 包运行 SwiftLint 的简单方法
- c++ - 如何将 CSV 文件集成到 OMNeT++ 最新版本中?
- ios - 带有故事板 segues 的上下文菜单预览提供程序
- reactjs - 如何将 iFrame 导出为 PDF
- spring-boot - 在 Spring Boot 中发送有关错误发生的电子邮件
- r - tools::toTitleCase vs stringr::str_to_title:出了什么问题?
- javascript - React 协调算法的入口点是什么?
- typescript - 如何在 TS 中存根全局函数