Python动态对象生成的困惑
我正在编写一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
其中目录是您关心的文件名的列表,这是一种非常常见的模式。如果你想要一个包含关键字文件名的字典,你可以这样做:
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:
@nmichaels 的答案是最干净、最Pythonic 的方法。更短的方法是:
编辑:哦,我看到你想要一本字典,即使你的伪代码创建了一个列表。您可以这样做:
解释:
dict
接受一个对象,该对象在迭代时会产生元组并将其转换为字典,例如@nmichaels answer is the cleanest and most Pythonic way to do it. An even shorter way would be:
EDIT: oh I see you wanted a dictionary, even though your pseudocode makes a list. You can do this:
Explanation:
dict
takes an object that when iterated over yields tuples and turns them into a dictionary, e.g.