【发布时间】:2011-10-24 14:02:04
【问题描述】:
我正在尝试在 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] 我希望在函数参数中指定它。
【问题讨论】:
-
也许我只是愚蠢,但你的问题似乎很困惑。值 2 和 6 用于调用中的 item1_pos 和 item2_pos(args 为空),但它们稍后看起来好像是 args(以某种奇怪的方式,对我来说毫无意义)。
-
@andrewcooke 抱歉,我发现这很混乱。我更新了我的问题,所以我希望现在更清楚了。
-
嗯。初始代码块中也应该是
yield(dict1[item1][item1_pos], dict2[item2][item2_pos])吗? -
即使这样我也不知道你所说的“每个字典项的其他值”是什么意思。例如,您的意思是要查看 dict1[item1] 中的条目 1、5 和 23 以及 dict2[item2] 中的条目 3、15 和 22?
-
我同意安德鲁的观点。我不明白你正在寻找的用法。您希望使用 *args 做什么?能给我举个例子吗? *args 就像函数中的参数列表一样。我不完全确定您还打算传递什么以及这些项目位置?您能否还包括 dict1 和 dict2 数据结构的示例,以及您希望如何看到理想的结果?
标签: python dictionary python-3.x match args