用于聚合行的Python代码

时间:2017-05-11 04:54:05

标签: python-3.x

寻找将转换以下行的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

2 个答案:

答案 0 :(得分:0)

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

由于堆栈溢出不是我们代码为你的网站我只描述了这个想法,而不是整个python代码。

答案 1 :(得分: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

但是,如果匹配,则在内部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)