使用Python 3.3
嗨,我对编程/Python还很陌生,所以请不要讨论太深入/复杂的方法来解决这个问题。你知道吗
我有一个字典,其中键是这个人的名字,每个键的值都是这个人朋友的名字列表。例如:
friends_of_person = {'Albus': ['Ron', 'Hermione'], 'Harry': ['Ron', 'Hermione', 'Neville']}
这本词典可以再长一些。你知道吗
我的问题是,如何编写一个for循环或代码来循环遍历这些值,并将每个值与另一个键的值进行比较。为了让这更清楚,让我们使用上面的例子。阿不思是哈利、罗恩和赫敏的朋友。哈利是罗恩和赫敏的朋友。你知道吗
但我想把“罗恩”和《哈利波特》中的“罗恩”、“赫敏”和“内维尔”作一个比较。 然后我想看看“罗恩”是不是哈利的朋友。如果罗恩是哈利的朋友,那么我想让“哈利”成为“阿不思”的潜在朋友。这一案例适用于将“赫敏”与哈利价值观中的“罗恩”和“赫敏”进行比较的情况。-这就像是共同的朋友。你知道吗
下面是我编写的代码,但似乎没有给出正确的答案。你知道吗
friends_of_person = {'Albus': ['Ron', 'Hermione'], 'Harry': ['Ron', 'Hermione', 'Neville']}
for person in friends_of_person:
friends_list = friends_of_person[person]
for friend in friends_list:
recommendation = ''
for another_person in friends_of_person:
if friend in friends_of_person[another_person]:
recommendation = another_person
好像不对。但如果有人能给我提示/提示,让我走上正确的方向,我将不胜感激!你知道吗
提前感谢:)
如果您只想使用简单的迭代和基本功能,请选择:
附言,这很难看,但那正是OP想要的。。。你知道吗
使用^{} 检查好友列表的交集:
@zhangxaochen使用集合的答案在我看来是最整洁的。尽管如此,如果您想使用列表,您可以执行以下操作:
请注意,这是重新编码集交集(编辑:如果已指示您不要使用集交集,则此解决方案是好的,因为您自己编码:))。你知道吗
所以呢
基本上,对于给定的人
x
,找到所有与他们有一个以上共同朋友的人。如果你想要两个共同的朋友,你可以把它改成== 2
。你知道吗相关问题 更多 >
编程相关推荐