【发布时间】:2017-12-19 03:59:53
【问题描述】:
我正在编写一个脚本来计算给定主网络地址的子网数量和地址。我有 2 个函数(目前)——AvailableNetworks() 和 BroadcastAddy()。我想在 2 列中打印这些函数,因此每一行都包含一个网络 ID,以及该子网的广播地址。 为此:第一列需要包含 AvailableNetworks() 的输出。第二列需要有BroadcastAddy()的输出。
我的最终目标是将 .format() 与“{:^30}{:^30}{:^30}”一起使用。但是,.format() 似乎在遍历列表列表时存在重大问题,或者至少我在告诉它如何这样做时遇到了重大问题。
这是我编写的两个函数:
MainNetwork = input("What is the main network id address?")
SubnetsDesired = input("How many subnets do you want to create?")
GoodNets = []
BroadcastAddresses = []
def AvailableNetworks():
NetArray = [2, 4, 8, 16, 32, 64, 128, 256]
HostArray = [256, 128, 64, 32, 16, 8, 4, 2]
for i in NetArray:
if i >= int(SubnetsDesired):
NumbSubnets = i
SubnetIndex = NetArray.index(i)
NumIps=HostArray[SubnetIndex + 1]
print("Available Networks:")
ipaddy = MainNetwork.split(".")
ipaddy = list(map(int, ipaddy))
for i in range(NumbSubnets-1):
ipaddy[-1] += NumIps
GoodNets.append('.'.join(str(i) for i in ipaddy))
break
def BroadcastAddy():
NetArray = [2, 4, 8, 16, 32, 64, 128, 256]
HostArray = [256, 128, 64, 32, 16, 8, 4, 2]
for i in NetArray:
if i >= int(SubnetsDesired):
NumbSubnets = i
SubnetIndex = NetArray.index(i)
NumIps = HostArray[SubnetIndex + 1]
print("Broadcast Adress:")
ipaddy = MainNetwork.split(".")
ipaddy = list(map(int, ipaddy))
for i in range(NumbSubnets - 1):
ipaddy[-1] += NumIps -1
BroadcastAddresses.append('.'.join(str(i) for i in ipaddy))
ipaddy[-1] += 1
break
我使用 zip() 将 Goodnets 的元素与具有相同索引号的广播地址的元素结合起来。
if __name__== '__main__':
AvailableNetworks()
BroadcastAddy()
# This combines lists so
FinalReport = zip(GoodNets, BroadcastAddresses)
# zip() creates immutable tuples that will give you hell if you try to run them through .format()
# So I convert FinalReport back into list of lists
FinalReport = [list(elem) for elem in FinalReport]
# Bug check (Delete this before final)
print("this is the type of final report:", type(FinalReport))
# Bug check, print the FinalReport to see what inside.
print(FinalReport)
# Formatted, when combined with .format() will create 2 columns. I've printed to column titles
# to prove this works.
formatted = "{:^30}{:^30}"
print(formatted.format("Network Addresses", "Broadcast Addresses"))
# Now, I try to print FinalReport in 2 columns.
for list in FinalReport:
for num in list:
print(formatted.format(num, num))
break
如前所述,我已尽我所能地查阅了文献,但我没有找到任何说明如何在一列中打印一个函数的输出以及在紧邻的一列中打印第二个函数的输出的任何文档。不过我可能是错的。非常感谢这个美妙的社区可以提供的任何帮助。谢谢。
【问题讨论】: