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 容器类型是什么?) 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01