我试图在我的代码中使用 set() 来跳过迭代中的重复值;此类问题可能已在 SO 上得到解答,但是当我尝试在我的脚本中执行此操作时,我没有得到所需的输出。
我正在使用 device['name'] 提取设备名称,API 中的 IP 地址为;这是 IP 地址的此类设备的 API 响应主体:
"DTO": [
{
"id": "3485893021",
"name": "Alternate Addresses",
"IPAddress": [
"10.228.143.125",
"10.228.143.253",
"10.229.184.125",
"10.229.184.134",
"192.21.247.125",
"192.21.247.188",
"192.21.247.226",
"192.21.247.254",
"192.21.247.61",
"192.21.247.92",
"192.168.53.38",
"192.128.167.74"
]
我有一个像上面一样的单个设备的多个 IP,但是当我尝试这个时,我将所有迭代的设备名称设为 None 并且只打印来自各个设备的第一个 IP。我想要的是打印所有 IP 并只打印一次它们对应的设备名称。我正在从 API 中提取这些数据。
seen = set()
seen_add = seen.add
for device in data:
fqdn = device['name']
for ips in device["DTO"][0]["IPaddress"]:
if fqdn not in seen:
print(ips, seen_add(fqdn))
这是输出:
10.228.143.125 None
10.23.54.6.8 None
10.23.6.1 None
10.22.16.34 None
10.122.25.189 None
我在 python 控制台输出中期待这个:
10.228.143.125 10.228.143.253 10.229.184.125 10.229.184.134 192.21.247.125 192.21.247.188 192.21.247.226 192.21.247.254 192.21.247.61 192.21.247.92 192.168.53.38 192.128.167.74 devicename1
等等其他此类设备......
更新:这个完全按照我想要的方式打印,但是现在当我尝试在 CSV 文件上打印它时,fqdn 和 ipaddresses 开始分崩离析。谁能帮助我以更简单的方式写这个?
for device in data:
fqdn = device['name']
if fqdn not in entries:
entries.add(fqdn)
print("\nDevice: %s" % fqdn)
for ips in device["DTO"][0]["IPaddress"]:
try:
ipaddress.ip_address(ips)
print(ips)
except ValueError:
print("Not Found")
python控制台上的输出:
Device: Device1
Not Found
Device: Device2
Not Found
Device: Device3
10.228.143.125
10.228.143.253
10.229.184.125
10.229.184.134
192.21.247.125
192.21.247.188
192.21.247.226
我试过这个打印在一个 csv 文件上:
with open("BNA API.csv", 'w', newline='') as f:
fieldname = ['BNA Name', 'IP Addresses']
writer = csv.DictWriter(f, fieldnames=fieldname)
writer.writeheader()
红糖糍粑
德玛西亚99
相关分类