如何打印第一个值和最后一个值?

2024-05-15 16:07:08 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的部分代码打印子网中的所有主机IP地址,我想修改代码,以便它只打印此列表的起始地址和最后一个地址

如何使用数组打印第一个和最后一个值?在

import ipaddress
print('enter subnet')  # in CIDR Format
x = input()
IP= ipaddress.ip_network(x, strict = False)
for y in IP.hosts():
 print(y)

电流输出

^{pr2}$

期望输出

HostMin:   192.0.0.1  
HostMax:   192.0.0.6

=========================================

更新:

在使用了这个列表之后,我可以打印第一个和最后一个值

however this takes quite longer to compute whenever i give a large
subnet

like 192.0.0.0/8 takes longer to print the first and last value, 

for: IPV6 address calculations it hangs forever, 
for: example: the  IPV6 address is 2001:db8::1/96 

this list will have 4294967294 elements since this IPV6 subnet has
these many IP address and it hangs forever to print the first and
last element of the list

Tags: andtheto代码inip列表for
3条回答

list[0]和{}分别获得第一个和最后一个元素

import ipaddress
print('enter subnet')  # in CIDR Format
x = input()
IP= ipaddress.ip_network(x, strict = False)
k = list(IP.hosts())
print("HostMin: ",k[0])
print("HostMax: ",k[-1])

更新的答案,以获得第一个和最后一个IP,而不生成整个IP范围

^{pr2}$

for y in IP.hosts():替换为y = list(IP.hosts()),然后您可以

print y[0]
print y[-1]

您应该阅读hosts()函数“返回网络中可用主机上的迭代器”的文档

这里不使用数组。使用列表!在

first_item = list[0]
last_item = list[-1]

相关问题 更多 >