首页 > 解决方案 > 键值更改时重新启动循环

问题描述

我正在尝试创建一个循环,该循环将打印组名及其在每个循环上的关联成员。在以下几行中,我将 [key] 设为组的字母,而 [value] 将设为名称。

this is to set use my user group A user john
this is to set use my user group A user joe
this is to set use my user group B user mary
this is to set use my user group B user nancy
with open(file_in) as ip, open('file_group_script.txt', 'w') as panscript:
    print("config addrgrp")
        dup_groups = set()
        host = []
        members = {}
        for line in ip:
            key, value = line[7],line[9]
            lines = line.strip().split()
            if len(lines) > 9:
                if re.search('group', lines[6]):
                    if lines[7] not in dup_groups:
                        print(f'group name "{lines[7]}"')
                        dup_groups.add(lines[7])
                        members[line[7]] = line[9]
                        print(members)

它打印出组名,但对于成员,我得到的只是:

group name A
{'u': 'i'}
{'u': 'i'}
group name B
{'u': 'i'}
{'u': 'i'}

标签: python-3.xfor-loop

解决方案


dup_groups不需要该集合,并且字段索引关闭了一个。

试试这个代码:

ss = '''
this is to set use my user group A user john
this is to set use my user group A user joe
this is to set use my user group B user mary
this is to set use my user group B user nancy
'''.strip()

with open('test.dat','w') as f: f.write(ss)  # write test file

####################################

import re

file_in = 'test.dat'

with open(file_in) as ip, open('file_group_script.txt', 'w') as panscript:
    host = []
    members = {}
    for line in ip:
        key, value = line[7],line[9]
        fields = line.strip().split()
        if len(fields) > 9:
            if re.search('group', fields[7]):
                if fields[8] in members.keys():  # if list exists
                    members[fields[8]].append(fields[10])  # append to list
                else:
                    members[fields[8]] = [fields[10]] # start list
                print(members)
                
print('\nFinal\n',members)

输出

{'A': ['john']}
{'A': ['john', 'joe']}
{'A': ['john', 'joe'], 'B': ['mary']}
{'A': ['john', 'joe'], 'B': ['mary', 'nancy']}

Final
 {'A': ['john', 'joe'], 'B': ['mary', 'nancy']}

推荐阅读