Useful alternative control structures?

后端 未结 28 922
礼貌的吻别
礼貌的吻别 2021-01-30 02:20

Sometimes when I am programming, I find that some particular control structure would be very useful to me, but is not directly available in my programming language. I think my

28条回答
  •  执笔经年
    2021-01-30 02:49

    How about iterating with a moving window (of n elements instead of 1) through a list? This is tangentially related @munificent's answer, I think.

    Something like

    #python
    #sum of adjacent elements
    for x,y in pairs(list):
        print x + y
    
    def pairs(l):              
        i=0                    
        while i < len(l)-1:    
            yield (l[i],l[i+1])
            i+=1               
    

    It is useful for certain types of things. Don't get me wrong, this is easy to implement as a function, but I think a lot of people try to bring out for and while loops when there are more specific/descriptive tools for the job.

提交回复
热议问题