Issue
I have the following code, which works fine. However, as I am very new to Python, there is still space to improve. I would like you to suggest to me the best way to handle this particular case and meanwhile, I can learn from it.
# Find all methods belonging to this header
custom_methods_of_the_current_header = [method for method in fmt_data if
method["type"] == constants.CUSTOM_METHOD and method[
"parent_id"] == header_id]
custom_methods_of_the_current_header_ordered = []
for i in range(1, len(ordered_list) - 1):
for j in range(len(custom_methods_of_the_current_header)):
if custom_methods_of_the_current_header[j]["name"] == ordered_list[i].gg.kind:
custom_methods_of_the_current_header_ordered.insert(i - 1,
custom_methods_of_the_current_header[j])
else:
continue
The code there are 3 lists.
custom_methods_of_the_current_header list is getting every matches item and adds inside. ex ["header01", "header03", "header02"]
ordered_list is the list had the ordered item ex. ["mainHeader", "header03", "header01", "header02", "footer"] , as main header and footer are not important, that is why starts range from 1 to 3
custom_methods_of_the_current_header_ordered list I am using to add the final ordered list by comparing custom_methods_of_the_current_header with ordered_list, as the ordered_list the header03 should be the first, then find the header03 in the current header list and adding it in the first index [0, header03]
The code itself works and accomplishes what I need, however, I wonder if I can optimize it to make it look cleaner and reduce the loop and complexity. Thanks in advance
Solution
You can probably benefit from removing the multiple inserts and the explicit indexing as follows:
custom_methods_of_the_current_header = [
method
for method in fmt_data
if method.get("type") == constants.CUSTOM_METHOD
and method.get("parent_id") == header_id
]
custom_methods_of_the_current_header_ordered = []
for oli in ordered_list[1:-1]:
tl = []
for cmoch in custom_methods_of_the_current_header:
if cmoch["name"] == oli.gg.kind:
tl.append(cmoch)
custom_methods_of_the_current_header_ordered += tl[::-1]
Answered By - CtrlZ
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.