Python:编号没有按预期工作

Python: Numbering doesn't work as expected

这段代码几乎完美,但是第二个编号没有按预期工作。

user@linux:~$ cat ip.txt 
10.1.1.1
10.2.2.2
10.3.3.3
user@linux:~$

script.py

from netmiko import Netmiko

with open('ip.txt') as f:
    print('List of Hosts')
    print('-' * 13)
    for x,y in enumerate(f.read().split(), 1):
        print(f'{x} - {y}')
    f.seek(0)
    ip_list = f.read().splitlines()
    print('\nNo  Hostname \t IP Address')
    print('-' * 27)
    for ip in ip_list:
        net_connect = Netmiko(ip=ip, device_type='cisco_ios', username='u',password='p',secret='p')
        hostname = net_connect.find_prompt()[:-1]
        print(f'{x}    {hostname} \t  {ip}')

输出

user@linux:~$ python3 script.py 
List of Hosts
-------------
1 - 10.1.1.1
2 - 10.2.2.2
3 - 10.3.3.3

No  Hostname     IP Address
---------------------------
3    R1       10.1.1.1
3    R2       20.2.2.2
3    R3       30.3.3.3
user@linux:~$

期望的输出

user@linux:~$ python3 script.py 
List of Hosts
-------------
1 - 10.1.1.1
2 - 10.2.2.2
3 - 10.3.3.3

No  Hostname     IP Address
---------------------------
1    R1       10.1.1.1
2    R2       20.2.2.2
3    R3       30.3.3.3
user@linux:~$

更新:

with open('ip.txt') as f:
    print('List of Hosts')
    print('-' * 13)
    for x,y in enumerate(f.read().split(), 1):
        print(f'{x} - {y}')
    f.seek(0)
    ip_list = f.read().splitlines()
    print('\nNo  Hostname \t IP Address')
    print('-' * 27)
    for ip in ip_list:
        net_connect = Netmiko(ip=ip, device_type='cisco_ios', username='u',password='p',secret='p')
        hostname = net_connect.find_prompt()[:-1]
        for x, ip in enumerate(ip_list,1):
            print(f'{x}    {hostname} \t  {ip}')

输出:

user@linux:~$ python3 script.py 
List of Hosts
-------------
1 - 10.1.1.1
2 - 10.2.2.2
3 - 10.3.3.3

No  Hostname     IP Address
---------------------------
1    R1       10.1.1.1
2    R1       10.2.2.2
3    R1       10.3.3.3
1    R2       10.1.1.1
2    R2       10.2.2.2
3    R2       10.3.3.3
1    R3       10.1.1.1
2    R3       10.2.2.2
3    R3       10.3.3.3
user@linux:~$ 

您没有在第二个循环中设置 x,因此它只是使用第一个循环中剩下的最后一个值。

像在第一个循环中那样使用 enumerate()

    for x, ip in enumerate(ip_list):
        net_connect = Netmiko(ip=ip, device_type='cisco_ios', username='u',password='p',secret='p')
        hostname = net_connect.find_prompt()[:-1]
        print(f'{x}    {hostname} \t  {ip}')```