Python:遍历对象在某些地方和最后执行代码

标签 python list code-duplication

这里有一些示例代码来解释:

outputText=""
counter=0
for obj in specialObjects:
    if (obj.id < 400) or (obj.name.startswith("he")) or (obj.deliberateBreak==True):
        print "The object %s is causing a section break."%obj.details
        outputText = outputText.rjust(80)
        open("file%d.txt"%counter,"w").write(outputText)
        outputText=""
    outputText+=obj.shortValue()
# THIS CODE IS DUPLICATED
outputText = outputText.rjust(80)
open("file%d.txt"%counter,"w").write(outputText)

我需要做的是遍历这些特殊对象的列表并每次检查几个不同的条件。如果满足任何条件(如此处所示),那么我需要获取当前输出缓冲区,将其写入文件,然后启动一个新的输出缓冲区并继续处理。

这里的问题是代码重复。请注意这两行(outputText= 和 open)是如何重复的。如果我没有放入第二组行,最后一组对象将被处理,但它们的输出将永远不会被写入。

我可以想到两种可能的解决方案来防止代码重复。两者都显得有些不雅,所以我想知道是否有更好的方法。

1) 包装将在函数中重复的代码。

outputText=""
counter=0
for obj in specialObjects:
    if (obj.id < 400) or (obj.name.startswith("he")) or (obj.deliberateBreak==True):
        print "The object %s is causing a section break."%obj.details
        counter = writeData(outputText)
        outputText=""
    outputText+=obj.shortValue()
writeData(outputText,counter)

def writeData(outputText,counter):
    outputText = outputText.rjust(80)
    open("file%d.txt"%counter,"w").write(outputText)
    return counter+1

2) 改为使用数字循环,并计数到比对象列表的长度大一;使用该值作为标志来表示“写入,但现在退出”:

outputText=""
counter=0
for obj in range(len(specialObjects))+1:
    if (obj = len(specialObjects)) or (specialObjects[obj].id < 400) or (specialObjects[obj].name.startswith("he")) or (specialOejcts[obj].deliberateBreak==True):
        print "The object %s is causing a section break."%specialObjects[obj].details
        outputText = outputText.rjust(80)
        open("file%d.txt"%counter,"w").write(outputText)
        outputText=""
        if (obj==len(specialObjects)):
            break 
    outputText+=specialObjects[obj].shortValue()

如果我必须选择一个,我可能会选择 #2,但如果需要使用任何更复杂的 bool 逻辑,这最终可能会使用“if”语句创建一些奇怪的边缘情况。

是否有更简洁或更“Pythonic”的方式来完成此任务而无需重复代码?

谢谢!

最佳答案

当我发现自己在编写这样的代码时,我在迭代一个集合并在循环结束后重复代码,我通常认为这表明我没有迭代正确的东西。

在这种情况下,您要遍历对象列表。但我认为,您真正想要迭代的是对象的列表。这就是 itertools.groupby 是有用的。

您的代码有很多内容,所以我将使用一个简化的示例来说明如何摆脱重复的代码。比如说,对于(一个非常人为的)例子,我有一个这样的列表:

things = ["apples", "oranges", "pears", None, 
          "potatoes", "tomatoes", None,
          "oatmeal", "eggs"]

这是一个对象列表。仔细看,有几组对象被None分隔开来(请注意,您通常会将 things 表示为嵌套列表,但为了示例的目的让我们忽略它)。我的目标是在单独的行中打印出每个组:

apples, oranges, pears
potatoes, tomatoes
oatmeal, eggs

这是执行此操作的“丑陋”方式:

current_things = []
for thing in things:
    if thing is None:
        print ", ".join(current_things)
        current_things = []
    else:
        current_things.append(thing)

print ", ".join(current_things)

如您所见,我们有重复的 print循环之后。讨厌!

这是使用 groupby 的解决方案:

from itertools import groupby

for key, group in groupby(things, key=lambda x: x is not None):
    if key:
        print ", ".join(group)

groupby采用可迭代(things)和关键功能。它查看可迭代对象的每个元素并应用 key 函数。当键改变值时,一个新的组就形成了。结果是一个返回 (key, group) 的迭代器对。

在这种情况下,我们将使用 None 的检查成为我们的关键职能。这就是为什么我们需要 if key: , 因为将有大小为 1 的组对应于 None我们列表的元素。我们将跳过这些。

如您所见,groupby允许我们迭代我们真正想要迭代的东西:对象的。这对于我们的问题来说更自然,代码也因此得到简化。看起来您的代码与上面的示例非常相似,只是您的 key 函数将检查对象的各种属性 ( obj.id < 400 ... )。我将把实现细节留给你...

关于Python:遍历对象在某些地方和最后执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27511260/

相关文章:

python - 代码重复和性能之间的权衡

python - 在 python 中查找对称对

在第一个结果处停止的 JavaScript 过滤器

python - 获取 ['76 125 94 95 122 96 126 123 124 87' 中的最高数字]?

python - PyGTK:允许在 AccelGroup 中使用 Tab

java - 使 Android/Java 代码更高效 - 删除重复项

c++ - 防止代码重复 : 2 long functions differing only in inner loop

python - 在 Python 中,这是一个好习惯吗?

python - 如何在 Django 网页的表格中显示我的 python 代码?

python - 用 Python : x12a and x13as not found on path 进行 ARIMA 季节性预测