无法使用 for 循环遍历嵌套列表来编辑内部列表

Trouble iterating through a nested list using a for loop to edit the inner lists

我只是不知道如何管理一些 arp 表。唯一与我相关的数据是 IP 地址和列出的 mac 地址。我不知道我是否应该,

  1. 遍历 nested_list,删除 [0, 2, 4, 5]

  2. 遍历列表,将 [1][3] 分配给新列表。

两种方法我都试过了,就是没成功。我的语法知识明显不足。

在您将要看到的任何代码之前,我先使用 with/as 访问一个文件,然后使用 .readlines() 创建一个字符串列表,我称之为 read_output.

这是我现在的代码:

nested_list = []

for index in read_output: 
    nested_list.append(index.split()) #this creates the nested list.

print(nested_list)

哪个工作正常并给我这个输出作为例子:

[['Internet', '10.220.88.1', '135', '0062.ec29.70fe', 'ARPA', 'FastEthernet4'],
 ['Internet', '10.220.88.40', '144', '001c.c4bf.826a', 'ARPA', 'FastEthernet4']]

arp 列表可能比这大很多,但我想我会为我们的示例保留一些 space。我希望能够按我认为合适的方式浏览列表和 add/remove/extract 数据,但每次尝试都会遇到不同程度的失败。

如果我只是:

print(nested_list[0][3])

我得到了 0062.ec29.70fe 的预期结果,但是当我尝试使用第二个 for 循环访问每个 [n][0][n][2] 等时,事情变得非常糟糕。

我开始于:

for index in read_output:
    nested_list.append(index.split())
    for indx in nested_list:
    # --->insert some horrible excuse for python here

我的预期输出是采用上面的嵌套列表并将其缩减为:

[['10.220.88.1', '0062.ec29.70fe'],
 ['10.220.88.40', '001c.c4bf.826a']]

首先不要附加整个子列表,而只附加您想要的两项:

nested_list = []

for index in read_output: 
    inner = index.split()
    nested_list.append([inner[1], inner[3]]) 

好的,所以我希望我理解正确,但据我了解,您正在正确获取数据,即:

[['Internet', '10.220.88.1', '135', '0062.ec29.70fe', 'ARPA', 
'FastEthernet4'],
 ['Internet', '10.220.88.40', '144', '001c.c4bf.826a', 'ARPA', 
'FastEthernet4']]

所以你是正确的,这实际上是一个列表,包含两个子列表。我们可以在下面的代码中利用这一点。

list = [['Internet', '10.220.88.1', '135', '0062.ec29.70fe', 'ARPA', 'FastEthernet4'],['Internet', '10.220.88.40', '144', '001c.c4bf.826a', 'ARPA', 'FastEthernet4']]

现在我们已经包含了该列表,与您所做的类似,我们可以遍历该列表。

for item in list:
    print ("IP: {0}\nMac Address:{1}\n".format(item[1],item[3]))

这给了我希望你期待的输出是:

IP: 10.220.88.1
Mac Address: 0062.ec29.70fe

IP: 10.220.88.40
Mac Address: 001c.c4bf.826a

所以我们所做的是 运行 循环遍历外部列表,因为我们知道 IP 地址总是位于内部列表的索引 1 和 3 处,所以我们只是访问它们通过他们的索引。

您不需要 运行 另一个循环遍历内部列表,因为您已经知道它们的位置。

要存储这些地址,您可能希望将它们存储在 字典,因为你有一个键值对类型的设置。

address = {}
count += 1
for item in list:
    count += 1
    address["list: {0}".format(count)] = [item[1], item[3]]
    print ("IP: {0}".format(item[1])
    print ("Mac Address: {0}".format(item[3]))
    print ()
print (address)

有了这个,我们设置了一个计数来增加我们的键名,并且对于每个新列表,我们将我们想要的两个特定值保存在另一个列表中。 一个很好的挑战是看看如何将它转换为您的密钥是 ip 和 mac 并且您的值是值的形式。 我考虑过这样做,但它甚至让我有点困惑,我想尽快把我的答案告诉你。希望这对您有所帮助!