“为了"循环第一次迭代 [英] "For" loop first iteration

查看:38
本文介绍了“为了"循环第一次迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想询问是否有一种优雅的 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?

这篇关于“为了"循环第一次迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆