“For” loop first iteration

前端 未结 13 2379
渐次进展
渐次进展 2020-12-04 15:17

I would like to inquire if there is an elegant pythonic way of executing some function on the first loop iteration. The only possibility I can think of is:

f         


        
13条回答
  •  感情败类
    2020-12-04 15:46

    I think the first S.Lott solution is the best, but there's another choice if you're using a pretty recent python (>= 2.6 I think, since izip_longest doesn't seem available before that version) that lets doing different things for the first element and successive one, and can be easily modified to do distinct operations for 1st, 2nd, 3rd element... as well.

    from itertools import izip_longest
    
    seq = [1, 2, 3, 4, 5]
    
    def headfunc(value):
        # do something
        print "1st value: %s" % value
    
    def tailfunc(value):
        # do something else
        print "this is another value: %s" % value
    
    def foo(value):
        print "perform this at ANY iteration."
    
    for member, func in izip_longest(seq, [headfunc], fillvalue=tailfunc):
        func(member)
        foo(member)
    

提交回复
热议问题