我在調試下面的函數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
感謝球員們,我意識到我的編輯器出現了問題,並且沒有正確運行我的代碼。 –