寻找可以转换以下代码行的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
发布于 2017-05-11 13:30:56
看一下replace函数。您基本上想要实现的是替换每个接口后的第二个"ALLOWED_VLAN“。您还可以使用find来获取该子字符串的第一个匹配项。之后,您将从那里开始搜索find,并获得第二个"ALLOWED_VLAN“的索引。然后,您可以将字符串拆分为该子字符串之前和子字符串之后的部分,并将这两个部分连接起来。
由于堆栈溢出是没有我们的代码为您的网站,我只描述了想法,但没有完整的python代码。
发布于 2017-05-11 14:17:39
这是可行的:
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)
https://stackoverflow.com/questions/43906802
复制相似问题