Head and tail in one line

后端 未结 5 635
独厮守ぢ
独厮守ぢ 2020-11-29 00:32

Is there a pythonic way to unpack a list in the first element and the \"tail\" in a single command?

For example:

>> head, tail = **some_magic a         


        
5条回答
  •  误落风尘
    2020-11-29 00:56

    Building on the Python 2 solution from @GarethLatty, the following is a way to get a single line equivalent without intermediate variables in Python 2.

    t=iter([1, 1, 2, 3, 5, 8, 13, 21, 34, 55]);h,t = [(h,list(t)) for h in t][0]
    

    If you need it to be exception-proof (i.e. supporting empty list), then add:

    t=iter([]);h,t = ([(h,list(t)) for h in t]+[(None,[])])[0]
    

    If you want to do it without the semicolon, use:

    h,t = ([(h,list(t)) for t in [iter([1,2,3,4])] for h in t]+[(None,[])])[0]
    

提交回复
热议问题