作者:NightyNight
链接:https://www.zhihu.com/question/50356943/answer/308811523
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
def _reshape(shaper, recursive_types):
fn_lst = [_reshape(e, recursive_types) if e.__class__ in recursive_types else next for e in shaper]
ret_cls = shaper.__class__
def apply(itor):
return ret_cls(fn(itor) for fn in fn_lst)
return apply
def reshape(shaper, recursive_types=(list, tuple, set)):
_apply = _reshape(shaper, set(recursive_types))
def apply(seq):
return _apply(iter(seq))
return apply
shaper = [(1, 2, 3, 6), {2, 3, 6}, [2, [2]]]
print(shaper)
from collections import Iterable
flatten = lambda nested: list(filter(lambda _: _,
(lambda _: ((yield from flatten(e)) if isinstance(e, Iterable) else (yield e) for e in _))(nested)))
lst = flatten(shaper)
print(lst)
reshaper = reshape(shaper)
print(reshaper(lst))
这个东西是parser。上面代码里的模型(reshape, _reshape),我认为就是parser的精髓(话说上面这个确实可以直接拿来当parser用)
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。