gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 05:30:18 26 4
gpt4 key购买 nike

我正在用 Python 编写一个 ImageCollection 类,它应该包含一个带有名称和图像对象(pygame.image 对象)的字典。

在一种情况下,我想将文件夹内的所有图像加载到字典中,而在另一种情况下,我只想加载特定文件,例如仅按钮文件。

到目前为止我写的是这样的:

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)})

唯一的问题是这可能是一种糟糕的编程模式,对吧?在这种情况下,这可能无关紧要,但我想知道这种情况下的最佳做法是什么。

当唯一的区别只是一个 if 条件时,我如何避免在两个不同的函数中重复自己?

我已经尝试创建一个创建条目的“dict_add”函数。然后我在想我可以创建两个不同的函数,一个直接调用“dict_add”,另一个检查特定条件然后调用“dict_add”。然后我想我可以添加仅使用 for 循环创建一个函数,但将一个函数作为参数传递(我假设这将是一个回调?)。但是一个回调需要一个额外的参数,所以这就是我卡住的地方,想知道我的方法是否正确。

最佳答案

您可以使 contains_str 成为一个可选参数

  • 如果您想加载图像 - 您只需提供路径
  • 在您想要加载特定图像的情况下 - 您提供 pathcontains_str 参数

在这两种情况下,您都调用 load_images(...)

代码:

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)})

关于python - 如何避免在两个不同的函数中重复 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74737609/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com