以元组为参数在UDF中解压缩元组

问题描述 投票:2回答:1

我正在尝试创建一个函数,该函数接受一个值是元组的字典,并使用一个独立的元组作为参数,然后,我试图在它们的索引值之间进行比较,如下所示。如果它们匹配,则应将密钥输入到新词典中。

我一直在尝试使用元组拆包,但是我不确定自己做错了什么(Python新手:]

some_dict = {"a" : (1,2,3), "b" : (1,4,5), "c" : (2,2,3)}
some_tuple = (1,2,5)

def function (some_dict, *some_tuple):
    another_dict = {"match" : [], "no_match" : []}
    some_tuple = list(some_tuple)
    for item in some_dict.values():
        if some_dict[item][0] == some_tuple[0]:
            another_dict["match"].append(item)
        else:
            another_dict["no_match"].append(item)
    return another_dict
python python-3.7 iterable-unpacking
1个回答
0
投票

调用该函数时,首先需要将*放在some_tuple前面。或者,您也可以在功能定义的*前面删除some_tuple

[另外,当您遍历some_dict时,我认为您不想使用values方法。因为我相信您想遍历dict的关键。

尝试以下操作:

some_dict = {"a": (1, 2, 3), "b": (1, 4, 5), "c": (2, 2, 3)}
some_tuple = (1, 2, 5)


def function(some_dict, *some_tuple):
    another_dict = {"match": [], "no_match": []}
    some_tuple = list(some_tuple)
    for item in some_dict:
        if some_dict[item][0] == some_tuple[0]:
            another_dict["match"].append(item)
        else:
            another_dict["no_match"].append(item)
    return another_dict


print(function(some_dict, *some_tuple))
{'match': ['a', 'b'], 'no_match': ['c']}
© www.soinside.com 2019 - 2024. All rights reserved.