我有以下代码,它运行得很好.然而,由于我对Python非常陌生,仍有改进的空间.我希望你能向我建议处理这一特殊情况的最佳方法,同时,我可以从中吸取教训.

            # 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是 list 上有订购的项目EX.["mainHeader","Header03","Header01","Header02","Footer"],因为主页眉和页脚并不重要,所以开始的范围是1到3

custom_methods_of_the_current_header_ordered列表我用来添加最终的有序列表,方法是将Custom_Methods_of_the_Current_Header与Order_List进行比较,因为Order_List中的Header03应该是第一个,然后在当前Header列表中找到Header03并将其添加到第一个索引[0,Header03]中

代码本身工作并完成了我所需要的,然而,我想知道我是否可以优化它,使它看起来更干净,并减少循环和复杂性.提前谢谢你

推荐答案

您可能会从删除多个插入和显式索引中受益,如下所示:

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]

Python相关问答推荐

Python在tuple上操作不会通过整个单词匹配

如何计算两极打印机中 * 所有列 * 的出现次数?

如何检测背景有噪的图像中的正方形

难以在Manim中正确定位对象

如何根据参数推断对象的返回类型?

' osmnx.shortest_track '返回有效源 node 和目标 node 的'无'

Julia CSV for Python中的等效性Pandas index_col参数

关于Python异步编程的问题和使用await/await def关键字

如何更改groupby作用域以找到满足掩码条件的第一个值?

在Python中调用变量(特别是Tkinter)

dask无groupby(ddf. agg([min,max])?''''

matplotlib + python foor loop

在Docker容器(Alpine)上运行的Python应用程序中读取. accdb数据库

如何在Python 3.9.6和MacOS Sonoma 14.3.1下安装Pyregion

你能把函数的返回类型用作其他地方的类型吗?'

为什么后跟inplace方法的`.rename(Columns={';b';:';b';},Copy=False)`没有更新原始数据帧?

如何在Python中自动创建数字文件夹和正在进行的文件夹?

在matplotlib中重叠极 map 以创建径向龙卷风图

使用pythonminidom过滤XML文件

是否将列表分割为2?