python - 根据可能出现多次的关键词拆分列表

标签 python python-3.x list ciscoconfparse

我已经阅读了看起来相似的示例,但我还没有达到理解答案的水平。我想获取列表输出并将每个接口(interface)编写为单独的行(又名我写入csv的列表)。我需要根据关键字“interface Vlan*”拆分初始返回列表

我想将关键字接口(interface) vlan* 上返回的列表 vlanlist 拆分为单独的列表

from ciscoconfparse import CiscoConfParse
import os

for filename in os.listdir():
    if filename.endswith(".cfg"):
        p = CiscoConfParse(filename)
        vlanlist=(p.find_all_children('^interface Vlan'))
        vlanlist.insert(0,filename)

        print(vlanlist) 

这是一行输出。我需要将关键字 "interface vlanxxx" 的列表拆分为单独的行

[ 'interface Vlan1', ' no ip address', ' shutdown', 'interface Vlan2003', ' description XXXXXX', ' ip address 10.224.6.130 255.255.255.224', ' no ip redirects', ' no ip unreachables', ' no ip proxy-arp', ' load-interval 60', ' arp timeout 420']

所需的输出(这可能有 2-20 个不同的接口(interface),我想根据配置文件进行拆分)

['interface Vlan1' ' no ip address', ' shutdown']
['interface Vlan2003', ' description XXXXXX', ' ip address 10.224.6.130 255.255.255.224', ' no ip redirects', ' no ip unreachables', ' no ip proxy-arp', ' load-interval 60', ' arp timeout 420']

最佳答案

在附加文件名之前,您可以进一步分隔返回的 vlanlist:

# First, find the index in the list where "interface Vlan" exists:
# Also, append None at the end to signify index for end of list
indices = [i for i, v in enumerate(l) if v.startswith('interface Vlan')] + [None]

# [0, 3, None]

# Then, create the list of lists based on the extracted indices and prepend with filename
newlist = [[filename] + vlanlist[indices[i]:indices[i+1]] for i in range(len(indices)-1)]

for l in newlist: print(l)

# ['test.cfg', 'interface Vlan1', ' no ip address', ' shutdown']
# ['test.cfg', 'interface Vlan2003', ' description XXXXXX', ' ip address 10.224.6.130 255.255.255.224', ' no ip redirects', ' no ip unreachables', ' no ip proxy-arp', ' load-interval 60', ' arp timeout 420']

第二个列表理解的解释:

newlist = [
    [filename] +                   # prepend single-item list of filename
    vlanlist[                      # slice vlanlist
        indices[i]:                # starting at the current index
        indices[i+1]               # up to the next index
    ] 
    for i in range(len(indices)-1) # iterate up to the second last index so i+1 doesn't become IndexError
]

如果您不喜欢索引方法,可以尝试使用zip:

lists = [[filename] + vlanlist[start:end] for start, end in zip(indices[:-1], indices[1:])]

关于python - 根据可能出现多次的关键词拆分列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52953391/

相关文章:

python - 如何将基于 tkinter 的应用程序与自定义图标捆绑在一起?

python - 程序跳过列表元素

python - 如何解决Eval()函数引起的错误?

python - 我可以让相同值的不同变量指向不同的对象吗?

python - 更改列表的元素会影响/不影响派生列表

python - 如何将多个列表附加到 python 字典中的一个键?

java - 列表问题

python - 使用 PIL 将 RGB 转换为 HSV

python - 使用 Matplotlib Python 绘图时跳过丢失的时间戳

python - 如何释放 SWIG 返回的 malloc'ed char*