import string def rmap(func, sequence): return [rmap(func, i) if isinstance(i, (tuple, list)) #elif isinstance(i, dict) ??? else func(i) for i in sequence] class mpCmd(dict): """Stores user defined maps and performs the map operations """ def __init__(self, map_dict, offset=0, int_is_index=True, str_is_name=False): self.offset = offset self.int_is_index = int_is_index self.str_is_name = str_is_name # just call __setitem__ and be done with it for k in map_dict.keys(): self[k] = map_dict[k] def __setitem__(self, key, val): key, val = self.__convert_item(key, val) super(mpCmd, self).__setitem__(key, val) def __convert_item(self, key, val): return self.__convert_key(key), self.__convert_val(val) def __convert_val(self, val): if isinstance(val, int) and self.int_is_index: index = val - self.offset return (lambda row, index=index: row[index]) elif isinstance(val, str) and self.str_is_name: index = self.__name_to_index(val) return (lambda row, index=index: row[index]) # not acceptable check elif isinstance(val, (tuple, list)): func, indexes = val return (lambda args: func(*rmap((lambda i: args[i]), indexes))) else: return (lambda *args, **kwargs: val) def __convert_key(self, key): if isinstance(key, str): return self.__name_to_index(key) elif isinstance(key, int): return key - self.offset else: raise TypeError def __name_to_index(self, col_name): return reduce((lambda index, char: index*26 + int(char, 36) - 9), col_name, 0) - 1 cmd = mpCmd({ 0: (''.join, [[19,7,8,18,8,18,0,13,4,23,15,0,17,17,14,19]]), 1: (sum, ([1, 3, 5, 4], 4)) }) print(cmd[0](string.ascii_uppercase)) print(cmd[1]([-2431, 3333, -40000, 3333, 1, 3333])) print(3333+3333+3333+1+1)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question