quot;Forquot; loop first 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?
这篇关于“为了"循环第一次迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“为了"循环第一次迭代


基础教程推荐
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01