3 回答

TA贡献1815条经验 获得超6个赞
使用这个数据集来测试代码:
data = [
{
"name": "device1",
"vendorName": "Cisco",
"DTO": [
{
"id": "426945997-254",
"name": "Category",
"IPaddress": [
"10.228.143.125",
"10.228.143.253",
"10.229.184.125",
"10.229.184.134",
"192.21.247.125"
],
}
]
},
{
"name": "device2",
"vendorName": "Cisco",
"DTO": [
{
"id": "426945997-254",
"name": "Category",
"IPaddress": [
],
}
]
},
{
"name": "device3",
"vendorName": "Cisco",
"DTO": [
{
"id": "426945997-254",
"name": "Category",
}
]
}
]
我不确定你到底在做什么,因为你的代码与键名不匹配,但这应该适合你
import csv
with open("BNA API.csv", 'w', newline='') as f:
fieldname = ['BNA Name', 'IP Addresses']
writer = csv.DictWriter(f, fieldnames=fieldname)
writer.writeheader()
with open("BNA API.csv", 'a', newline='') as f:
for device in data:
fqdn = device['name']
try:
ips = ' '.join(set(device["DTO"][0]["IPaddress"])) or "not found"
except KeyError:
ips = "not found"
writer = csv.writer(f)
writer.writerow([fqdn, ips])
ips = ' '.join(set(device["DTO"][0]["IPaddress"])) or "not found"正在检查,如果IP地址为空的清单是用Python的True-Y检测的意义如果集合返回空它会采取"not found"替代
编辑:似乎这个问题还有更多内容,如果您的 IP 地址不正确或没有什么,您可以' '.join()像这样使用过滤器:
bad_list = ['Firewall','Load something']
#...
#same code
try:
ips = ' '.join(x for x in set(device["DTO"][0]["IPaddress"]) if x not in bad_list) or "not found"
if x not in bad_list在将其添加到 之前的检查.join(),您可以将其视为在遍历列表时的过滤器。如果您不想键入要排除的所有内容,您可以将其更改为if ipaddress(x)并编写一个调用的函数ipaddress(x),如果它是有效的 ipaddress,则返回 True,如果不是,则返回 false。

TA贡献1770条经验 获得超3个赞
两个建议:
1) seen_add做了一些事情,但它不返回任何东西,这就是给你 None 的。
2)如果你不希望它们被换行分开,你不能在for循环中打印,你只需要一个打印。您可以随时构建字符串:out_str = out_str + ' ' + ips
如果你不关心顺序,一点点展平应该可以工作:
print(' '.join{ips for device in data for ips in device["DTO"][0]["IPaddress"]})
添加回答
举报