I have a function shown below:
def _extract_parent(matched_list, json_data, info_type):
return [json_data[match_lst][info_type] for match_lst in matched_list]
parent_lst = list(map(lambda x: _extract_parent(x,json_data, "parent_info"), flashtext_matched_pattern))
family_lst = list(map(lambda x: _extract_parent(x, json_data, "family_info"),flashtext_matched_pattern))
This code works for me. But I wish to optimize it I keep calling the map from the outside instead I want to do the mapping inside the _extract_parent function and call the function like
res = _extract_parent(flashtext_matched_pattern, json_data, "parent_info")
My JSON looks like this:
{ "power series": {
"parent_info" : "abc",
"family_info" : "xyz",
"base_info" : "pqr"
}
}
flashtext_matched_pattern is a list of list which looks like below. It can have empty list as well as values shown in the example
[[],
['power series'],
[],
[],
[],
[]]
So if the power series is matched it will give me the info I requested example parent_info or family_info.
Now I wish to optimize the code. I want to augment _extract_parent function to include mapping part too and call the _extract_parent function like
parent_lst = _extract_parent(flashtext_matched_pattern, json_data, "parent_info")
family_lst = _extract_parent(flashtext_matched_pattern, json_data, "family_info")
How can I do the same? Any help in this would be highly appreciated
Or am I thinking in the wrong direction would it be a better solution? If for each matching entry, return a tuple containing metadata parent, family and base info. (If yes how to do that)
CodePudding user response:
Your long statements where you call your code via map
and a lambda
are just an inconvinient way of doing another list comprehension:
parent_lst = [_extract_parent(x,json_data, "parent_info")
for x in flashtext_matched_pattern]
If you want to do everything in to the function, you can make that happen with a nested list comprehension:
def _extract_parent(list_of_match_lists, json_data, info_type):
return [
[json_data[match][info_type] for match in match_list]
for match_list in list_of_match_lists
]