名前といくつかのクエリを含むテキスト ファイルを書き込むプログラムがあります。最初の 4 行は、左側に親の図を定義し、コロンの後にその子を定義することから始まります。もしそうなら、それを家系図と考えてください。この演習では、辞書を使用してこの問題を解決するよう求めています。
これがファイルの始まりです..
test_file = open('relationships.txt', 'w')
test_file.write('''Sue: Chad, Brenda, Harris
Charlotte: Tim
Brenda: Freddy, Alice
Alice: John, Dick, Harry
mother Sue
mother Charlotte
mother Brenda
mother Dick
''')
test_file.close()
出力は ..
Mother not known
Mother not known
Sue
Alice
mother
子供がどの母親に属しているかを確認するこのクエリを作成する方法がわかりません。私はいくつかのことを試しました..
parents = {}
for line in lines[0:4]:
parent, child = line.strip().split(':')
if parent in parents:
parents[parent] += str(child)
else:
parents[parent] = str(child)
print(parents)
この時点で、誰の母親が誰であるかにアクセスして把握する方法に行き詰まっています。私が考えることができる唯一の他の方法は、キーと値を入れ替えて、すべての子供の母親を個別にラベル付けする行の膨大なリストを作成することです。