“For” loop first iteration

前端 未结 13 2341
渐次进展
渐次进展 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:34

    Your question is contradictory. You say "only do something on first iteration", when in fact you are saying do something different on first/subsequent iterations. This is how I would attempt it:

    copyfn = root.copy
    for member in something.get():
        copyfn(member)
        foo(member)
        copyfn = somewhereElse.copy
    
    0 讨论(0)
  • 2020-12-04 15:39

    I think this is quite elegant, but maybe too convoluted for what it does...

    from itertools import chain, repeat, izip
    for place, member in izip(chain([root], repeat(somewhereElse)), something.get()):
        place.copy(member)
        foo(member)
    
    0 讨论(0)
  • 2020-12-04 15:40

    Something like this should work.

    for i, member in enumerate(something.get()):
        if i == 0:
             # Do thing
        # Code for everything
    

    However, I would strongly recommend thinking about your code to see if you really have to do it this way, because it's sort of "dirty". Better would be to fetch the element that needs special handling up front, then do regular handling for all the others in the loop.

    The only reason I could see for not doing it this way is for a big list you'd be getting from a generator expression (which you wouldn't want to fetch up front because it wouldn't fit in memory), or similar situations.

    0 讨论(0)
  • 2020-12-04 15:40

    If something.get() iterates over something, you can do it also as follows:

    root.copy(something.get())
    
    for member in something.get():
      #  the rest of the loop
    
    0 讨论(0)
  • 2020-12-04 15:42

    This works:

    for number, member in enumerate(something.get()):
        if not number:
            root.copy(member)
        else:
            somewhereElse.copy(member)
        foo(member)
    

    In most cases, though, I'd suggest just iterating over whatever[1:] and doing the root thing outside the loop; that's usually more readable. Depends on your use case, of course.

    0 讨论(0)
  • 2020-12-04 15:44

    Here is what works for me

        dup_count = 0
        for x in reversed(dup_list):
            dup_count += 1
            if dup_count == 1:
                print("First obj {}: {}".format(dup_count,x))
            else:
                print("Object # {}:  {}".format( dup_count,x  ))
    
    0 讨论(0)
提交回复
热议问题