我正在编写一个脚本来计算给定主网络地址的子网的数量和地址。我有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的元素与具有相同索引号的Broadcast Addresses元素组合在一起。
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
如上所述,我尽可能地回顾了文献,但我没有找到任何文档,教导如何在一列中打印一个函数的输出,在紧邻列中打印第二个函数。我可能错了。非常感谢这个精彩社区所能提供的任何帮助。谢谢。
我认为你要做的事情将通过以下方式得到纠正:
for list in FinalReport:
print(formatted.format(list[0], list[1]))
您之前的每次迭代都将采用以下形式:
['192.168.1.32', '192.168.1.31']
随着你的内部qazxsw poi循环,你迭代在列表qazxsw poi中的第一个元素,然后调用for
所以永远不会到达第二个元素。
提供的代码片段将迭代列表列表并通过它的相对索引访问每对。