开发者

Python Dynamic Object Generation Confusion

I'm writing a Python script that takes a directory, and for each file of a sp开发者_运维技巧ecific 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?


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)


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


my_objects = {name:customObject(name) for name in dir if isMyType(name)}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜