如何在函数signatu中使用dict值

2024-04-18 11:34:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些清单里面有迪克特

list_of_dict = [
    {'row_n': 1, 'nomenclature_name': 'some_nomenclature_name', 'article': '', 'TM': ''}, 
    {'row_n': 2, 'no_category': '', 'nomenclature_name': 'some_nomenclature_name', 'article': '', 'TM': ''}
]

我把这张单子翻译一下。你知道吗

uniq_nomenclature_names_from_imported_file = {value['nomenclature_name'] for value in list_of_dict if value['nomenclature_name'] != ''}

因为这个逻辑可以重用,所以我想做一些方法 重新定义它。所以,我的问题是,如何处理函数签名中的dict值,例如:

def some_reusable_func(list_of_dict, dict_value):
        return uniq_nomenclature_names_from_imported_file = {value['dict_value'] for value in list_of_dict if value['dict_value'] != ''}


def my_case_with_list_of_dict():
    some_reusable_func(
        list_of_dict = some_list_of_dict,
        dict_value = 'some_dict_value'
)

我将非常感谢你的帮助。你知道吗


Tags: ofnamefromnamesvaluearticlesomedict
3条回答

为了好玩,我尝试创建list的子类,并将函数作为方法添加到其中。你知道吗

class my_list(list):
    def get_names(self, name):
        return {value[name] for value in self if value.get(name) and value[name] != ''} 

list_of_dict = my_list([
    {'row_n': 1, 'nomenclature_name': 'some_nomenclature_name', 'article': '', 'TM': ''}, 
    {'row_n': 2, 'no_category': '', 'nomenclature_name': 'some_nomenclature_name', 'article': '', 'TM': ''},
])

print(list_of_dict.get_names('nomenclature_name'))

结果

{'some_nomenclature_name'}
def some_reusable_func(list_of_dict, k):
    return {i[k] for i in list_of_dict if i[k] != ''}

赋值是一个语句,而不是表达式,不能返回赋值值,否则会导致错误invalid syntax

试验

print(some_reusable_func(list_of_dict, 'nomenclature_name'))
# {'some_nomenclature_name'}

也可以使用lambda函数。你知道吗

some_reusable_func = lambda list_of_dict, k: {i[k] for i in list_of_dict if i[k] != ''}
some_reusable_func(list_of_dict, 'nomenclature_name')

您可以直接使用dict_value变量作为键来访问,而不是在理解中使用字符串'dict_value'(并且只返回set,而不返回=,这将引发SyntaxError):

def some_reusable_func(list_of_dict, dict_value):
        return {value[dict_value] for value in list_of_dict if value[dict_value] != ''}

相关问题 更多 >