Python动态对象生成的困惑

发布于 2024-10-25 06:22:32 字数 385 浏览 1 评论 0原文

我正在编写一个 Python 脚本,该脚本采用一个目录,并为该目录中特定类型的每个文件创建一个字典或自定义对象。

我感觉自己像个白痴,但是当我开始实际创建字典的部分时......我对如何实例化和跟踪动态对象感到困惑。

#Pseudocode
for each conf file in given directory:
    x = customObject('filename') # variable name fail
    track_list.append(customObject('filename')) # this seems weird

我应该创建这些对象并将它们添加到列表中吗?人们通常如何做到这一点?我觉得我正在尝试编写可以编写更多代码的代码?

I'm writing a Python script that takes a directory, and for each file of a specific type in that directory, creates a dictionary or custom object.

I feel like an idiot, but when I get to the part of actually creating the dictionary..I'm confused on how to instantiate and track the dynamic objects.

#Pseudocode
for each conf file in given directory:
    x = customObject('filename') # variable name fail
    track_list.append(customObject('filename')) # this seems weird

Should I be creating these objects and adding them to a list? How do people usually do this? I feel like I'm trying to write code that writes more code?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

深海夜未眠 2024-11-01 06:22:32
track_list = [custom_object(filename) for filename in directory]

其中目录是您关心的文件名的列表,这是一种非常常见的模式。如果你想要一个包含关键字文件名的字典,你可以这样做:

custom_dict = dict((filename, custom_object(filename)) for filename in directory)
track_list = [custom_object(filename) for filename in directory]

where directory is a list of the file names you care about is a pretty common pattern. If you want a dictionary with file names for keywords, you can do this:

custom_dict = dict((filename, custom_object(filename)) for filename in directory)
宛菡 2024-11-01 06:22:32

@nmichaels 的答案是最干净、最Pythonic 的方法。更短的方法是:

track_list = map(customObject, directory)

编辑:哦,我看到你想要一本字典,即使你的伪代码创建了一个列表。您可以这样做:

result = dict((filename, customObject(filename)) for filename in directory)

解释:dict 接受一个对象,该对象在迭代时会产生元组并将其转换为字典,例如

>>> dict([('hey', 3), ('food', 4), ('haxhax', 6)])
{'food': 4, 'haxhax': 6, 'hey': 3}

@nmichaels answer is the cleanest and most Pythonic way to do it. An even shorter way would be:

track_list = map(customObject, directory)

EDIT: oh I see you wanted a dictionary, even though your pseudocode makes a list. You can do this:

result = dict((filename, customObject(filename)) for filename in directory)

Explanation: dict takes an object that when iterated over yields tuples and turns them into a dictionary, e.g.

>>> dict([('hey', 3), ('food', 4), ('haxhax', 6)])
{'food': 4, 'haxhax': 6, 'hey': 3}
走野 2024-11-01 06:22:32
my_objects = {name:customObject(name) for name in dir if isMyType(name)}
my_objects = {name:customObject(name) for name in dir if isMyType(name)}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文