gpt4 book ai didi

python - 具有设定长度的重建列表

转载 作者:太空宇宙 更新时间:2023-11-04 01:38:36 24 4
gpt4 key购买 nike

我正在构建一个 Python 脚本来对我们的内部系统进行网络清点。每个系统最多有五个集群,我正在寻找一种方法来调整列表以将它们全部放在每个集群的一行中。以下是它们在系统中的存储方式:

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)

我需要将它们调整为如下所示:

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)

这是我现在正在使用的一些非常草率的代码,但我想知道是否有更有效的方法来做到这一点:

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 的,所以这可能只是一个简单的调整。提前致谢。

最佳答案

初看: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']

关于python - 具有设定长度的重建列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7324163/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com