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


猜你喜欢
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01