我想询问在第一次循环迭代中是否存在一种优雅的pythonic方式来执行某些功能。我能想到的唯一可能性是:
first = True for member in something.get(): if first: root.copy(member) first = False else: somewhereElse.copy(member) foo(member)
头尾 设计模式有多种选择。
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)”代码。这是一个荒谬的说法。如果是这样,那么所有功能只能使用一次。如果只能有一个引用,定义一个函数有什么意义?