以下の関数get_secondary_connections
のデバッグに問題があります。なんらかの理由で、私のfor friend in network[user][‘connections’]
ループは、リスト全体をループするのではなく、リストの最初の値で常に停止します。なぜそれが当てはまるのか分かりません。誰かが私にこれに関するいくつかの指導を与えることができますか?本当にありがとう!ここで最初の繰り返し後にPython forループが停止する
は私のネットワークです:
network = {
'Freda': {'connections': ['Olive', 'John', 'Debra'], 'favorite games': ['Starfleet Commander', 'Ninja Hamsters', 'Seahorse Adventures']},
'Ollie': {'connections': ['Mercedes', 'Freda', 'Bryant'], 'favorite games': ['Call of Arms', 'Dwarves and Swords', 'The Movie: The Game']},
'Debra': {'connections': ['Walter', 'Levi', 'Jennie', 'Robin'], 'favorite games': ['Seven Schemers', 'Pirates in Java Island', 'Dwarves and Swords']},
'Olive': {'connections': ['John', 'Ollie'], 'favorite games': ['The Legend of Corgi', 'Starfleet Commander']},
'Levi': {'connections': ['Ollie', 'John', 'Walter'], 'favorite games': ['The Legend of Corgi', 'Seven Schemers', 'City Comptroller: The Fiscal Dilemma']},
'Jennie': {'connections': ['Levi', 'John', 'Freda', 'Robin'], 'favorite games': ['Super Mushroom Man', 'Dinosaur Diner', 'Call of Arms']},
'Mercedes': {'connections': ['Walter', 'Robin', 'Bryant'], 'favorite games': ['The Legend of Corgi', 'Pirates in Java Island', 'Seahorse Adventures']},
'John': {'connections': ['Bryant', 'Debra', 'Walter'], 'favorite games': ['The Movie: The Game', 'The Legend of Corgi', 'Dinosaur Diner']},
'Robin': {'connections': ['Ollie'], 'favorite games': ['Call of Arms', 'Dwarves and Swords']},
'Bryant': {'connections': ['Olive', 'Ollie', 'Freda', 'Mercedes'], 'favorite games': ['City Comptroller: The Fiscal Dilemma', 'Super Mushroom Man']},
'Walter': {'connections': ['John', 'Levi', 'Bryant'], 'favorite games': ['Seahorse Adventures', 'Ninja Hamsters', 'Super Mushroom Man']} }
そしてここでは、私のコードです:
def get_secondary_connections(network, user):
if user not in network:
return None
sec_connections = []
for friend in network[user]['connections']:
for connection in network[friend]['connections']:
if connection not in sec_connections:
sec_connections.append(connection)
return sec_connections
私はget_secondary_connections(ネットワーク、「メルセデス」)を実行すると、私は次のような出力が得られます。
[‘John’, ‘Levi’, ‘Bryant’]
私のネットワークでチェックインした場合、Walterの接続リストのみです。誰かが私を助けてくださいすることができ
[‘John’, ‘Levi’, ‘Bryant’, ‘Ollie’, ‘Olive’, Freda’, ‘Mercedes’]
:私はつまり、メルセデスのセカンダリ接続の完全なリストを取得することになっていますか?
再生できません。あなたのコードを実行すると、あなたの望む出力とまったく同じように見えます。 – luther
コードが正しいように見えます。入力が正しいと確信していますか? – stybl
ありがとうございました。エディタに何か問題があり、コードが正しく実行されていないことに気付きました。 –