简体   繁体   English

如何避免在两个不同的函数中重复 for 循环

[英]How can I avoid repeating a for loop in two different functions

I am writing an ImageCollection class in python that should hold a dictionary with a name and the image-object (pygame.image object).我正在 python 中编写一个 ImageCollection class,它应该包含一个带有名称和图像对象(pygame.image 对象)的字典。

In one case I want to load all images inside a folder to the dictionary and in another case just specific files, for example only button-files.在一种情况下,我想将文件夹内的所有图像加载到字典中,而在另一种情况下,我只想加载特定文件,例如仅按钮文件。

What I have written so far is this:到目前为止我写的是这样的:

class ImageCollection:
    def __init__(self):
        self.dict = {}
    
    def load_images(self, path):
        directory = os.fsencode(path)

        for file in os.listdir(directory):
            file_name = os.fsdecode(file)
            img_path = path + "/" + file_name

            if file_name.endswith(".jpg") or file_name.endswith(".png"):
                # Remove extension for dictionary entry name and add image to dictionary
                #-----------------------------------------------------------------------
                dict_entry_name = file_name.removesuffix(".jpg").removesuffix(".png")
                self.dict.update({dict_entry_name: image.Image(img_path, 0)})
    
    def load_specific_images(self, path, contains_str):
        directory = os.fsencode(path)

        for file in os.listdir(directory):
            file_name = os.fsdecode(file)
            img_path = path + "/" + file_name

            if file_name.endswith(".jpg") or file_name.endswith(".png"):
                if file_name.rfind(contains_str):
                    # Remove extension for dictionary entry name and add image to dictionary
                    #-----------------------------------------------------------------------
                    dict_entry_name = file_name.removesuffix(".jpg").removesuffix(".png")
                    self.dict.update({dict_entry_name: image.Image(img_path, 0)})

The only problem is that this is probably bad programming pattern, right?唯一的问题是这可能是糟糕的编程模式,对吧? In this case it probably doesnt matter but I would like to know what the best-practice in this case would be.在这种情况下,这可能无关紧要,但我想知道这种情况下的最佳做法是什么。

How can I avoid repeating myself in two different functions when the only difference is just a single if condition?当唯一的区别只是一个 if 条件时,如何避免在两个不同的函数中重复自己?

I have tried creating a "dict_add" function that creates the entry.我尝试创建一个创建条目的“dict_add”function。 Then I was thinking I could create two different functions, one which directly calls "dict_add" and the other one checks for the specific condition and then calls "dict_add".然后我在想我可以创建两个不同的函数,一个直接调用“dict_add”,另一个检查特定条件然后调用“dict_add”。 Then I thought I could add create just a single function with the for-loop but pass a function as an argument (which would be a callback I assume?).然后我想我可以使用 for 循环添加仅创建一个 function,但将 function 作为参数传递(我假设这将是一个回调?)。 But one callback would need an additional argument so thats where I got stuck and wondered if my approach was correct.但是一个回调需要一个额外的参数,所以这就是我卡住的地方,想知道我的方法是否正确。

You could make the contains_str an optional argument .您可以使contains_str成为可选参数

  • In cases where you want to load_images - you just provide the path在您想要加载图像的情况下 - 您只需提供path
  • In cases where you want to load specific images - you provide the path and the contains_str argument在你想要加载特定图像的情况下 - 你提供pathcontains_str参数

In both cases you call load_images(...)在这两种情况下,您都调用load_images(...)

Code:代码:

class ImageCollection:
    def __init__(self):
        self.dict = {}
    
    def load_images(self, path, contains_str=""):
        directory = os.fsencode(path)

        for file in os.listdir(directory):
            file_name = os.fsdecode(file)
            img_path = path + "/" + file_name

            if file_name.endswith(".jpg") or file_name.endswith(".png"):
                if contains_str == "" or (contains_str != "" and file_name.rfind(contains_str)):
                    # Remove extension for dictionary entry name and add image to dictionary
                    #-----------------------------------------------------------------------
                    dict_entry_name = file_name.removesuffix(".jpg").removesuffix(".png")
                    self.dict.update({dict_entry_name: image.Image(img_path, 0)})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何使python循环重复两个变量 - How can i make python loop repeating two variables 如何获得脚本和变量更改的重复功能 - How can I get repeating functions of a script and variable changes 如何避免对许多函数重复某些参数? (蟒蛇) - How to avoid repeating certain arguments for many functions? (Python) 我如何在下面的代码中使用 for loop 和.format 在不同的函数上 go? - how can i go over different functions using for loop and .format for my code below? 如何在循环中使用函数中的结果? - How can I use the results in functions in a loop? 循环写入 CSV 时如何避免重复 header? - How to avoid repeating header when Writing to CSV in loop? 如何使用列表来避免一遍又一遍地重复“和/或”运算符? - How can I use a list to avoid repeating 'and/or' operators over and over again? 如何针对收到的总请求的不同百分比调用两个函数? - How can I call two functions for different percentage of the total requests received? 如何在一个 HTML 页面 Django 中使用两种不同的功能 - How can I use two different functions in one HTML page Django 如何将来自不同函数的两个局部变量加在一起? - How can I add together two local variables from different functions?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM