我有一份名单里面有迪克特
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': ''}
]我在集合中翻译这个list_of_dict。
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'
)我会感谢你的帮助。
发布于 2019-08-31 12:37:18
您可以直接使用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] != ''}发布于 2019-08-31 12:42:58
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')发布于 2019-08-31 12:56:07
为了好玩,我尝试创建一个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'}https://stackoverflow.com/questions/57738064
复制相似问题