我正在尝试在 python 中构建一个函数,如果来自dict1
的特定值与dict2
. 我的功能如下所示:
def dict_matcher(dict1, dict2, item1_pos, item2_pos):
"""Uses a tuple value from dict1 to search for a matching tuple value in dict2. If a match is found, the other values from dict1 and dict2 are returned."""
for item1 in dict1:
for item2 in dict2:
if dict1[item1][item1_pos] == dict2[item2][item2_pos]:
yield(dict1[item1][2], dict2[item2][6])
我是这样使用dict_matcher
的:
matches = [myresults for myresults in dict_matcher(dict1, dict2 , 2, 6)]
print(matches)
当我打印时,matches
我得到一个正确匹配 dict1 和 dict2 值的列表,如下所示:
[('frog', 'frog'), ('spider', 'spider'), ('cricket', 'cricket'), ('hampster', 'hampster')]
如何向此函数添加变量参数,以便除了打印每个字典中的匹配值之外,我还可以在dict1[item1][2] and dict2[item2][6]
匹配的实例中打印每个字典项的其他值?我可以使用 *args 吗?谢谢您的帮助。
编辑:好的,我想做什么似乎有些混乱,所以让我试试另一个例子。
dict1 = {1: ('frog', 'green'), 2: ('spider', 'blue'), 3: ('cricket', 'red')}
dict2 = {a: ('frog', 12.34), b: ('ape', 22.33), c: ('lemur', 90.21)}
dict_matcher(dict1, dict2, 0, 0)
将从 dict1 中找到 value[0] 和从 dict2 中找到 value[0] 的匹配值。在这种情况下,唯一的匹配是'frog'。我上面的功能就是这样做的。我想要做的是扩展函数,以便能够从dict1[value][0] == dict2[value][0]
我希望在函数参数中指定的字典项中打印出其他值。