我想询问是否有一种优雅的Pythonic方法可以在第一次循环迭代中执行一些功能。我唯一能想到的可能性是:
first = True
for member in something.get():
if first:
root.copy(member)
first = False
else:
somewhereElse.copy(member)
foo(member)
答案
您有几个选择Head-Tail设计模式。
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 )
人们抱怨这不是"干燥",因为"冗余foo(成员)“代码。这是一个荒谬的说法。如果那是真的,那么所有功能只能使用一次。如果您只能有一个参考,则定义功能有什么意义?