如何使用字典和具有多个变量的函数创建for循环

时间:2019-02-27 14:03:20

标签: python

我正在努力创建一个for循环来解决这个问题,我正在尝试解决一个涉及dictionary的问题,该循环由员工ID 和他们的兴趣清单组成。这是字典,称为“ idkey”:

{'0': ['Hadoop', 'Big Data', 'HBas', 'Java', 'Spark', 'Storm', 'Cassandra'],
 '1': ['NoSQL', 'MongoDB', 'Cassandra', 'HBase', 'Postgres'],
 '2': ['Python', 'skikit-learn', 'scipy', 'numpy', 'statsmodels', 'pandas'],
 '3': ['R', 'Python', 'statistics', 'regression', 'probability'],
 '4': ['machine learning', 'regression', 'decision trees', 'libsvm'],
 '5': ['Python', 'R', 'Java', 'C++', 'Haskell', 'programming languages'],
 '6': ['statistics', 'probability', 'mathematics', 'theory'],
 '7': ['machine learning', 'scikit-learn', 'Mahout', 'neural networks'],
 '8': ['neural networks','deep learning','Big Data','artificial intelligence'],
 '9': ['Hadoop', 'Java', 'MapReduce', 'Big Data']}

我需要根据每个员工的兴趣来匹配他们。这是我编写的功能:

def InterestingFriends(employee1, employee2):
sharedinterests = list(set(idkey[employee1]).intersection(idkey[employee2]))
if len(sharedinterests) > 0:
    print("Employee", employee1, "and", employee2, "are a match based on their shared interest of", sharedinterests)
else:
    None

这是我在for循环中获得的

for e1 in list(idkey.keys()):
    InterestingFriends(e1, '0')

哪个输出:

Employee 0 and 0 are a match based on their shared interest of ['Spark', 'Storm', 'Big Data', 'Java', 'Cassandra', 'HBas', 'Hadoop']
Employee 1 and 0 are a match based on their shared interest of ['Cassandra']
Employee 5 and 0 are a match based on their shared interest of ['Java']
Employee 8 and 0 are a match based on their shared interest of ['Big Data']
Employee 9 and 0 are a match based on their shared interest of ['Java', 'Big Data', 'Hadoop']

很显然,我对此进行了硬编码。我似乎无法弄清楚如何在其中获取另一个变量以与其他每个员工进行迭代。有任何想法吗?我已经尝试过类似fore1的{​​{1}}循环,而不是 just e1 ,但是我总是收到错误消息。

1 个答案:

答案 0 :(得分:3)

您需要itertools.combinations,可以使用

获得所有键的组合。
import itertools

for e1, e2 in itertools.combinations( idkey.keys(), 2 ):
    InterestingFriends(e1,e2)

我认为这比嵌套的for循环更漂亮。