比较字典中的值

2024-06-16 08:57:16 发布

您现在位置:Python中文网/ 问答频道 /正文

使用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

好像不对。但如果有人能给我提示/提示,让我走上正确的方向,我将不胜感激!你知道吗

提前感谢:)


Tags: of代码inforanother朋友名字list
3条回答

如果您只想使用简单的迭代和基本功能,请选择:

for friend in friends_of_person['Albus']:
    recommendation = []
    for person, friends in friends_of_person.items():
        if person == 'Albus':
            continue # we don't need anyone who already is his friend
        for potential in friends:
            if potential in friends_of_person['Albus'] and potential not in recommendation:
                recommendation.append(potential)
print(potential)
   ...: 
Neville

附言,这很难看,但那正是OP想要的。。。你知道吗

使用^{}检查好友列表的交集:

In [352]: lst1=friends_of_person['Albus']

In [353]: lst2=friends_of_person['Harry']

In [354]: lst1
Out[354]: ['Ron', 'Hermione']

In [355]: lst2
Out[355]: ['Ron', 'Hermione', 'Neville']

In [356]: set(lst1)&set(lst2)
Out[356]: set(['Hermione', 'Ron'])

@zhangxaochen使用集合的答案在我看来是最整洁的。尽管如此,如果您想使用列表,您可以执行以下操作:

friends = {'Albus': ['Ron', 'Hermione'], 'Harry': ['Ron', 'Hermione', 'Neville']}

def mutual_friends(a, b):
    return [x for x in friends[a] if x in friends[b]]

请注意,这是重新编码集交集(编辑:如果已指示您不要使用集交集,则此解决方案是好的,因为您自己编码:))。你知道吗

所以呢

def recommendations(x):
    result = []

    for f in friends.keys():
        if f != x and mutual_friends(x, f) > 1:
            result.append(f)

    return result

基本上,对于给定的人x,找到所有与他们有一个以上共同朋友的人。如果你想要两个共同的朋友,你可以把它改成== 2。你知道吗

相关问题 更多 >