2017-05-11 32 views
0

寻找Python代码,将下面的行Python代码为聚合线

interface port-channel 1 
ALLOWED_VLAN 2,4-7,27,30-31,38-39,41-42,48-50 
ALLOWED_VLAN 74,678,1101-1102,1201-1202 
interface port-channel 2 
ALLOWED_VLAN 37,51-52,75-76,1051-1052,2001 
interface port-channel 101 
ALLOWED_VLAN 10,18-19,37,39,51-52,75-76,901-902 
ALLOWED_VLAN 2901-2902,3204,3305 

转换成

interface port-channel 1 
ALLOWED_VLAN 2,4-7,27,30-31,38-39,41-42,48-50,74,678,1101-1102,1201-1202 
interface port-channel 2 
ALLOWED_VLAN 37,51-52,75-76,1051-1052,2001 
interface port-channel 101 
ALLOWED_VLAN 10,18-19,37,39,51-52,75-76,901-902,2901-2902,3204,3305 

回答

0

看一看替换功能。你基本上想要实现的是在每个接口之后替换第二个“ALLOWED_VLAN”。 您也可以使用find来获取子字符串的第一个匹配项。之后,您将从那里开始搜索查找,并获取第二个“ALLOWED_VLAN”的索引。然后你可以在这个子字符串之前和子字符串之后拆分字符串并连接这两个部分。

由于堆栈溢出是没有我们代码为您的网站我只描述了想法,但不是整个Python代码。

+0

感谢塞巴斯蒂安,我会尝试, –

0

这工作:

lines = [] 

with open("file.txt", "r") as f: 
    for line in f: 
     lines.append(line.rstrip()) 

new_lines = [] 

i = 0 
while i < len(lines) - 1: 
    line = lines[i] 
    counter = 1 
    while i + counter < len(lines): 
     next_line = lines[i+counter] 
     if line.split()[0] == next_line.split()[0]: 
      line += "," + next_line.split()[-1] 
      counter += 1 
     else: 
      break 
    i += counter 
    new_lines.append(line) 

print(new_lines) 

结果:

[ 
'interface port-channel 1', 
'ALLOWED_VLAN 2,4-7,27,30-31,38-39,41-42,48-50,74,678,1101-1102,1201-1202', 
'interface port-channel 2', 
'ALLOWED_VLAN 37,51-52,75-76,1051-1052,2001', 
'interface port-channel 101', 
'ALLOWED_VLAN 10,18-19,37,39,51-52,75-76,901-902,2901-2902,3204,3305,2901-2902,3204,3305' 
] 

基本上,迭代算法贪婪地往下检查下一行的列表,看看第一个字是一样的。如果不是,立即打破内部while循环,只增加i,1

但是,如果存在匹配,则后续行会在inner while循环中消耗,直到if语句中断为止,并且i会增加消耗的行数。

因此,虽然循环是双重嵌套的,但仍具有O(n)的运行时间。不过,它最多可以使用O(2n)的空间。为了避免这种情况(如果您的列表是巨大的),你可以做替代突变(但这样会增加运行时间):

lines_to_remove = [] 

i = 0 
while i < len(lines) - 1: 
    line = lines[i] 
    counter = 1 
    while i+counter < len(lines): 
     next_line = lines[i+counter] 
     if line.split()[0] == next_line.split()[0]: 
      lines[i] += "," + next_line.split()[-1] 
      lines_to_remove.append(i + counter) 
      counter += 1 
     else: 
      break 
    i += counter 

for index in sorted(lines_to_remove, reverse=True): 
    del lines[index] 

print(lines) 
+0

感谢您的回答,但是这个问题我有我正在阅读从txt文件 –

+0

这不是一个问题 - 我只是没有包括它的简洁。你是否愿意阅读文件并获得python列表,或输出到另一个文件?我已经更新了示例以包含第一种情况 - 但如果您愿意,也可以添加文件输出。 – Darkstarone

+0

谢谢男人,我是新手编程,想哟学习更多,你是一个程序员,我想有你作为我的导师 –