“为了"循环第一次迭代

2022-01-24 00:00:00 python algorithm iteration

问题描述

我想询问是否有一种优雅的 Python 方式可以在第一次循环迭代时执行某些函数.我能想到的唯一可能是:

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:

first = True
for member in something.get():
    if first:
        root.copy(member)
        first = False
    else:
        somewhereElse.copy(member)
    foo(member)


解决方案

Head-Tail 设计模式有多种选择.

You have several choices for the Head-Tail design pattern.

seq= something.get()
root.copy( seq[0] )
foo( seq[0] )
for member in seq[1:]:
    somewhereElse.copy(member)
    foo( member )

或者这个

seq_iter= iter( something.get() )
head = seq_iter.next()
root.copy( head )
foo( head )
for member in seq_iter:
    somewhereElse.copy( member )
    foo( member )

人们抱怨这不是DRY",因为冗余 foo(member)"代码.这是一个荒谬的说法.如果这是真的,那么所有功能只能使用一次.如果你只能有一个引用,那么定义一个函数有什么意义呢?

People whine that this is somehow not "DRY" because the "redundant foo(member)" code. That's a ridiculous claim. If that was true then all functions could only be used once. What's the point of defining a function if you can only have one reference?

相关文章