我正在构建一个Python脚本来在我们的内部系统上进行网络清单。每个系统最多有五个集群,我正在寻找一种方法来调整列表,将它们全部放入每个集群一行。以下是它们存储在系统中的方式:
群集一 主要制度
节点一 x.x.x.x(节点IP)
节点二 x.x.x.x(节点IP)
集群二 主要制度
节点一 x.x.x.x(节点IP)
节点二 x.x.x.x(节点IP)
我需要将它们调整为这样:
群集一,主系统,节点一,x.x.x.x(节点IP),节点二,x.x.x.x(节点IP)
群集二,主系统,节点一,x.x.x.x(节点IP),节点二,x.x.x.x(节点IP)
这是我现在正在使用的一些非常糟糕的代码,但我想知道是否有更有效的方法来实现它:
NetworkTableCount = len(NetworkTable) / 6 + 1
count = 1
while count < NetworkTableCount:
if count == 1:
Temp = (NetworkTable[0]+","+NetworkTable[1]+","+NetworkTable[2]+","+NetworkTable[3]+","+NetworkTable[4]+","+NetworkTable[5]+"\n")
elif count == 2:
Temp = (NetworkTable[6]+","+NetworkTable[7]+","+NetworkTable[8]+","+NetworkTable[9]+","+NetworkTable[10]+","+NetworkTable[11]+"\n")
elif count == 3:
Temp = (NetworkTable[12]+","+NetworkTable[13]+","+NetworkTable[14]+","+NetworkTable[15]+","+NetworkTable[16]+","+NetworkTable[17]+"\n")
elif count == 4:
Temp = (NetworkTable[18]+","+NetworkTable[19]+","+NetworkTable[20]+","+NetworkTable[21]+","+NetworkTable[22]+","+NetworkTable[23]+"\n")
elif count == 5:
Temp = (NetworkTable[24]+","+NetworkTable[25]+","+NetworkTable[26]+","+NetworkTable[27]+","+NetworkTable[28]+","+NetworkTable[29]+"\n")
NetworkTopology.write(Temp)
count = count + 1
我在Python中自学,所以它可能只是一个简单的调整。提前谢谢。
答案 0 :(得分:2)
首先看一下:How do you split a list into evenly sized chunks?
使用其中一个答案:
>>> import itertools
>>> NetworkTable
['Cluster One', 'Primary System', 'Node One', 'x.x.x.x (Node IP)', 'Node two', 'x.x.x.x (Node IP)', 'Cluster Two', 'Primary System', 'Node One', 'x.x.x.x (Node IP)', 'Node two', 'x.x.x.x (Node IP)']
>>> l = [NetworkTable[i:i+6] for i in range(0, len(NetworkTable), 6)]
>>> l
[['Cluster One', 'Primary System', 'Node One', 'x.x.x.x (Node IP)', 'Node two', 'x.x.x.x (Node IP)'], ['Cluster Two', 'Primary System', 'Node One', 'x.x.x.x (Node IP)', 'Node two', 'x.x.x.x (Node IP)']]
>>> #Now it's easy. Do what you want with l.
>>> [", ".join(i) + "\n" for i in l]
['Cluster One, Primary System, Node One, x.x.x.x (Node IP), Node two, x.x.x.x (Node IP)\n', 'Cluster Two, Primary System, Node One, x.x.x.x (Node IP), Node two, x.x.x.x (Node IP)\n']
答案 1 :(得分:1)
我会根据它们开头的名称来处理这些行,因为它似乎是一个'Cluster'指定一组新的数据:
file = open('my_file')
clusters=[]
line = file.readline()
while line.strip().startswith("Cluster"):
cluster = []
cluster.append(line.strip())
line = file.readline()
cluster.append(line.strip())
line = file.readline()
while line.strip().startswith("Node"):
node = []
node.append(line.strip())
line = file.readline()
node.append(line.strip())
cluster.append(node)
line = file.readline()
clusters.append(cluster)
# now you have a list of clusters, where nodes are in a list too
print(clusters[0])
print(clusters[1])