for-loop - 在 for 循环中使用 'else' 的 Pythonic 方式

标签 for-loop python

<分区>

我几乎没有注意到在 for 循环中使用 else 的 python 程序。

我最近用它在退出时根据循环变量条件执行一个 Action ;因为它在范围内。

在 for 循环中使用 else 的 pythonic 方式是什么?有什么值得注意的用例吗?

而且,是的。我不喜欢使用 break 语句。我宁愿设置循环条件复杂。如果我无论如何都不喜欢使用 break 语句,我能从中获得任何好处吗?

值得注意的是,自语言诞生以来,for 循环就有了一个 else,这是有史以来的第一个版本。

最佳答案

还有什么比 PyPy 更 pythonic?

看看我在 ctypes_configure/configure.py 中从第 284 行开始发现的内容:

    for i in range(0, info['size'] - csize + 1, info['align']):
        if layout[i:i+csize] == [None] * csize:
            layout_addfield(layout, i, ctype, '_alignment')
            break
    else:
        raise AssertionError("unenforceable alignment %d" % (
            info['align'],))

在这里,来自 pypy/annotation/annrpython.py ( clicky ) 中的第 425 行

if cell.is_constant():
    return Constant(cell.const)
else:
    for v in known_variables:
        if self.bindings[v] is cell:
            return v
    else:
        raise CannotSimplify

在 pypy/annotation/binaryop.py 中,从第 751 行开始:

def is_((pbc1, pbc2)):
    thistype = pairtype(SomePBC, SomePBC)
    s = super(thistype, pair(pbc1, pbc2)).is_()
    if not s.is_constant():
        if not pbc1.can_be_None or not pbc2.can_be_None:
            for desc in pbc1.descriptions:
                if desc in pbc2.descriptions:
                    break
            else:
                s.const = False    # no common desc in the two sets
    return s

pypy/annotation/classdef.py 中的非单行代码,从第 176 行开始:

def add_source_for_attribute(self, attr, source):
    """Adds information about a constant source for an attribute.
    """
    for cdef in self.getmro():
        if attr in cdef.attrs:
            # the Attribute() exists already for this class (or a parent)
            attrdef = cdef.attrs[attr]
            s_prev_value = attrdef.s_value
            attrdef.add_constant_source(self, source)
            # we should reflow from all the reader's position,
            # but as an optimization we try to see if the attribute
            # has really been generalized
            if attrdef.s_value != s_prev_value:
                attrdef.mutated(cdef) # reflow from all read positions
            return
    else:
        # remember the source in self.attr_sources
        sources = self.attr_sources.setdefault(attr, [])
        sources.append(source)
        # register the source in any Attribute found in subclasses,
        # to restore invariant (III)
        # NB. add_constant_source() may discover new subdefs but the
        #     right thing will happen to them because self.attr_sources
        #     was already updated
        if not source.instance_level:
            for subdef in self.getallsubdefs():
                if attr in subdef.attrs:
                    attrdef = subdef.attrs[attr]
                    s_prev_value = attrdef.s_value
                    attrdef.add_constant_source(self, source)
                    if attrdef.s_value != s_prev_value:
                        attrdef.mutated(subdef) # reflow from all read positions

稍后在同一个文件中,从第 307 行开始,一个带有启发性注释的示例:

def generalize_attr(self, attr, s_value=None):
    # if the attribute exists in a superclass, generalize there,
    # as imposed by invariant (I)
    for clsdef in self.getmro():
        if attr in clsdef.attrs:
            clsdef._generalize_attr(attr, s_value)
            break
    else:
        self._generalize_attr(attr, s_value)

关于for-loop - 在 for 循环中使用 'else' 的 Pythonic 方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/685758/

相关文章:

python - Requirements.txt 大于等于然后小于?

Python合并两个计数器对象,保持最大的总和

Python Pandas (Excel) 数据表代码问题

python - PyQt4:如何在修改时更改子窗口的标题

c++ - 循环中的恒定条件 : compiler optimization

bash - 使用 for 循环在多个文件上运行 zcat

Java 单个 IF 语句内的不同数量的条件

Python 在函数内使用 For 循环

r - 如何使用 mutate 从 for 循环中的列表创建列

python - 从 BERT 获取嵌入查找结果