我正在尝试将居民作为居民的成员放入《词典》中。这样,如果我搜索Bill,它将返回在Res-Condo-2和Res-Condo-1处有一个Bill。我正在读取的文本文件如下:
************
Ohio
************
Res-House-1
Mickey
Minnie
Goofy
Res-Apt-1
Fred
Barnie
Wilma
Res-Condo-2
Bill
************
Ohio
************
Res-House-2
Stan
Francine
Haley
Stve
Res-Condo-1
Bill
我能够读取文件并创建驻留列表,但是我无法获取其他元素。我还注意到列表末尾包含换行符。
list = []
with open('Residencies') as f:
for line in o:
if "Res" in line:
list.append(line)
print(list)
打印语句输出
['Res-House-1\n', 'Res-Apt-1\n', 'Res-Codo-2\n', 'Res-House-2\n', 'Res-Condo-1\n']
如何获取字典中的每个住所,以便搜索哪个住所属于哪个住所?
答案 0 :(得分:1)
让我们先忽略不相关的行(例如,空行,***
等)
if line.startswith('*') or line.startswith(' '):
continue
line = line.strip()
if not line:
continue
现在,只需跟踪您见过的最后一个住所即可。该住所后面的所有名字都住在那里。将此信息放入字典中,以键为人名,值作为住所列表。
from collections import defaultdict
home = defaultdict(list)
last = None
with open('Residencies') as f:
for line in f:
if line.startswith('*') or line.startswith(' '):
continue
line = line.strip()
if not line:
continue
if 'Res' in line:
last = line
else:
home[line].append(last)
print(home['Bill'])
输出:['Res-Condo-2', 'Res-Condo-1']
此外,将list
作为变量的名称也不是一个好主意。
答案 1 :(得分:1)
按居民对居民进行分组:
from collections import defaultdict
with open('Residencies.txt') as f:
residencies = defaultdict(list)
for line in f:
line = line.strip()
if not line: continue # skip empty line
if line.startswith('**'): # skip *** state block
next(f)
next(f)
continue
if line.startswith('Res'):
k = line
continue
residencies[k].append(line)
print(dict(residencies))
输出:
{'Res-Apt-1': ['Fred', 'Barnie', 'Wilma'],
'Res-Condo-1': ['Bill'],
'Res-Condo-2': ['Bill'],
'Res-House-1': ['Mickey', 'Minnie', 'Goofy'],
'Res-House-2': ['Stan', 'Francine', 'Haley', 'Stve']}