[英]How to create a for loop with dictionary and function with multiple variables
我正在努力創建一個for
循環來解決這個問題,我正在嘗試解決一個涉及由員工ID和員工興趣列表組成的dictionary
的問題。 這是字典,稱為“ 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']
顯然,我對此進行了硬編碼。我似乎無法弄清楚如何在其中獲取另一個變量以與其他每個雇員進行迭代。 有任何想法嗎? 我已經嘗試了for
循環類似於上面e1
, e2
,而不是僅僅E1,但我總是得到一個錯誤。
您需要itertools.combinations,可以使用來獲取所有鍵的組合
import itertools
for e1, e2 in itertools.combinations( idkey.keys(), 2 ):
InterestingFriends(e1,e2)
我認為這比嵌套的for循環漂亮。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.