python-3.x - 键值更改时重新启动循环
问题描述
我正在尝试创建一个循环,该循环将打印组名及其在每个循环上的关联成员。在以下几行中,我将 [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'}
解决方案
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']}
推荐阅读
- algolia - InstantSearch.js v4.8.5 x search-insights 1.7.1 不发送点击事件
- microsoft-dynamics - 对 Dynamics 365 API 和访问采购订单的困惑
- python - Python - 如果仅在 'if __name__ == '__main__' 中调用它,它是否被视为私有方法?
- javascript - 如何修复“未找到模块:错误:无法解析 'mvc/form/form-repeat'”?
- python - Selenium 无法按名称找到表单元素
- python - Python程序为输入数字打印菱形图案?
- xcode - Xcode 12:分发内容页面仅显示 2 个选项
- python - 对齐菜单栏中的条目
- python - Python - 通过解包以太网帧获取 0xc0a8 期望 0x800 的类型不期望数据
- android - 当应用程序目标为(Android 11 / API 30)或更高版本时,如何将文件保存在android的根文件夹中?