首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在可能出现多次的关键字上拆分列表

在可能出现多次的关键字上拆分列表
EN

Stack Overflow用户
提问于 2018-10-23 16:01:21
回答 4查看 169关注 0票数 1

我读过那些看似相似的例子,但我并不是在那个层次去理解答案。我希望获得列表输出,并将每个接口写成一个单独的行(aka list I write to a csv)。我需要分割关键字‘接口Vlan*’上的初始返回列表

我希望将关键字接口vlan*上返回的列表vlanlist拆分为单独的列表。

代码语言:javascript
复制
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"上的列表拆分成不同的行

代码语言:javascript
复制
[ '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个不同的接口,我想根据配置文件来分割)

代码语言:javascript
复制
['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']
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2018-10-23 16:31:34

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

代码语言:javascript
复制
# 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']

对第二个清单理解的解释:

代码语言:javascript
复制
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

代码语言:javascript
复制
lists = [[filename] + vlanlist[start:end] for start, end in zip(indices[:-1], indices[1:])]
票数 1
EN

Stack Overflow用户

发布于 2018-10-23 16:26:38

这里有一个与您的单个测试用例高度耦合的解决方案。如果完整的数据集不能代表您的单个测试用例,那么您将不得不通过更多的测试来改进它。

代码语言:javascript
复制
def extract(items):
  result, filename, idx = [], items[0], -1

  for x in items[1:]:
    if x.startswith('interface Vlan'):
      idx += 1
      result.append([filename])
    result[idx].append(x)

  return result

# given & expected are your example and output 
assert expected == extract(given)

编辑:

..。你已经改变了输入和输出。

代码语言:javascript
复制
def extract(items):
  result, idx = [], -1

  for x in items:
    if x.startswith('interface Vlan'):
      idx += 1
      result.append([])

    if not result: continue  # assuming possible unwanted items before 'interface Vlan'
    result[idx].append(x)

  return result

assert expected == extract(given)
票数 1
EN

Stack Overflow用户

发布于 2018-10-23 16:48:42

一种快速而直接的解决方案。检查列表中的interface Vlan项,如果是的话,它会创建一个新列表,否则会追加到旧列表和一些.strip()上,以获得良好的度量。

代码语言:javascript
复制
output = ['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']

results = []

for i in output:
    if 'interface Vlan' in i:
        results.append([i.strip()])
    else:
        results[-1].append(i.strip())

>> results
 [['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']]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52953391

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档