开发者

How to make my code more simple using python

this is my code:

def set_floor_point(self,floor_point=None):
    if self.data.get('stage'):
        self.data['stage'] = {}
    stage_number = self.get_stage_number()
    floor_number = self.get_floor_number()

    if self.data['stage'].get(stage_num开发者_开发技巧ber):
        self.data['stage'][stage_number] = {}

    if self.data['stage'][stage_number].get('floor_point'):
        self.data['stage'][stage_number]['floor_point'] = {}

    if self.data['stage'][stage_number]['floor_point'].get(floor_number):
        self.data['stage'][stage_number]['floor_point'][floor_number] = {}


    self.data['stage'][stage_number]['floor_point'][floor_number] = floor_point

and the dict i create when first time is like this :

stage = 
{
    0:{
        'floor':{
            0:{
                'floor_point':0,
                'gift':{}
            }
        }
    }
}

but i think my code is not very good , it is too Cumbersome,

so Are someone know more simple way ,

thanks


data = collections.defaultdict(lambda: collections.defaultdict(
  lambda: collections.defaultdict(dict)))
data['stage'][3]['floor_point'][2] = 5
print data


I'm not sure what you want to achieve. A recurring theme in your code is:

if some_dict.get(key):
    some_dict[key] = {}

That means: if some_dict has a key key and some_dict[key] is a truthy value, then replace some_dict[key] by {}. If some_dict doesn't have a key key or some_dict[key] is a falsy value (None, 0, False, [] etc.), then do nothing.

If that is what you wanted, you could clarify your like this:

def replace_value_by_empty_dict(d, key):
    if d.get(key):
        d[key] = {}
...
replace_value_by_empty_dict(self.data, 'stage')
etc.

But if that's not what you intended (the code will break if one of the ifs is true), you might want to phrase the problem in english words or pseudocode to clarify the structure of the problem.

And have a look at collections.defaultdict.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜