我如何才能提高算法的速度,哪怕是最小的提高.由于我这样做的原因,我实际上丝毫不关心速度,但是我想知道如果我能改变什么.除了真正指出要更改的特定事物以外,我真正想知道的是如何知道有一种更有效的方法以及该方法如何工作.基本上,如果您想了解低级内容的工作方式,以便可以在较高级上编写更好的代码,应该遵循的路线.
How can I improve the speed of my algorithm, even by the slightest amount. For the reason I made this I don't actually care about speed in the slightest, but I'm wondering what I could change if I did. Even more than pointing out specific things to change, what I really want to know is how you know that there's a more efficient way and how that way works. Basically, what is the track to follow if you want to learn how the low level stuff works so that you can write better code at the higher level.
def decode_all(ob): if(type(ob)==list): for i in range(len(ob)): ob[i] = decode_all(ob[i]) if(type(ob)==dict): for i in ob.copy(): ob[i] = decode_all(ob[i]) if(type(i)==bytes): ob[i.decode()] = ob[i] ob.pop(i) if(type(ob)==tuple): new_ob = [] for i in ob: new_ob.append(decode_all(i)) ob = tuple(new_ob) if(type(ob)==bytes): return ob.decode() return ob 推荐答案修改后的代码:
def decode_all(ob): if isinstance(ob, list): return [decode_all(e) for e in ob] if isinstance(ob, dict): return {decode_all(k): decode_all(v) for k, v in ob.items()} if isinstance(ob, tuple): return tuple([decode_all(e) for e in ob]) if isinstance(ob, bytes): return ob.decode() return ob通常,我同意使用 if ... elif ... elif ... ,但是在这种情况下,立即返回结果会更简单.
Usually, I agree with the use of if ... elif ... elif ..., but in this case, it's simpler to just return the result right away.
一些注意事项:
一些替代方法:
从functools中的
from functools import singledispatch @singledispatch def decode_all(ob): return ob @decode_all.register def _(ob: bytes): return ob.decode() @decode_all.register def _(ob: list): return [decode_all(e) for e in ob] @decode_all.register def _(ob: dict): return {decode_all(k): decode_all(v) for k, v in ob.items()} @decode_all.register def _(ob: tuple): return tuple([decode_all(e) for e in ob])