繁体   English   中英

"在 for 循环中使用“else”的 Pythonic 方法"

[英]Pythonic ways to use 'else' in a for loop

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

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

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

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

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

还有什么比PyPy更具有Python风格的?

看一下我在c​​types_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循环,则实际上没有任何条件语句。 因此,如果您想中止,则选择休息是您的选择,然后其他方式可以很好地处理您不满意的情况。

for fruit in basket:
   if fruit.kind in ['Orange', 'Apple']:
       fruit.eat()
       break
else:
   print 'The basket contains no desirable fruit'

基本上,它简化了使用布尔标志的任何循环,如下所示:

found = False                # <-- initialize boolean
for divisor in range(2, n):
    if n % divisor == 0:
        found = True         # <-- update boolean
        break  # optional, but continuing would be a waste of time

if found:                    # <-- check boolean
    print n, "is composite"
else:
    print n, "is prime"

并允许您跳过标志的管理:

for divisor in range(2, n):
    if n % divisor == 0:
        print n, "is composite"
        break
else:
    print n, "is prime"

请注意,当您确实找到除数时,就已经有一个自然的地方可以执行代码了-在break之前。 唯一的新功能是在尝试所有除数但未找到任何除数时执行代码的地方。

这仅有助于break 如果不能中断,则仍然需要布尔值(例如,因为您正在寻找最后一场比赛,或者必须同时跟踪多个条件)。

哦,顺便说一句,这同样适用于while循环。

任何/全部

如今,如果循环的唯一目的是“是或否”答案,则可以使用具有生成布尔值的生成器或生成器表达式的any() / all()函数,将循环编写得更短:

if any(n % divisor == 0 
       for divisor in range(2, n)):
    print n, "is composite"
else:
    print n, "is prime"

注意优雅! 您想说的是1:1的代码!

[这就像带有一个break的循环一样有效,因为any()函数是短路的,只运行生成器表达式,直到产生True为止。 实际上,它通常比循环还要快。 较简单的Python代码往往不会听到过多的声音。]

如果您有其他副作用,例如,如果您想找到除数,则这种方法不太可行。 您仍然可以使用非零值在Python中为真这一事实(ab):

divisor = any(d for d in range(2, n) if n % d == 0)
if divisor:
    print n, "is divisible by", divisor
else:
    print n, "is prime"

但是正如您看到的那样,它变得不稳定-如果0是可能的除数值,则将无法工作...

如果不使用break ,则else块对于forwhile语句没有好处。 以下两个示例是等效的:

for x in range(10):
  pass
else:
  print "else"

for x in range(10):
  pass
print "else"

使用else with forwhile的唯一原因是,如果循环正常终止,则在循环后执行某些操作,这意味着无需显式break

经过深思熟虑,我终于可以提出一个可能有用的案例:

def commit_changes(directory):
    for file in directory:
        if file_is_modified(file):
            break
    else:
        # No changes
        return False

    # Something has been changed
    send_directory_to_server()
    return True

最好的答案也许来自官方的Python教程:

中断并继续执行语句,否则循环上的子句

循环语句可以包含else子句; 当循环通过用尽列表而终止(使用for)或条件变为假(使用while)时执行,但在使用break语句终止循环时不执行

向我介绍了一个很棒的习惯用法,您可以在其中使用带迭代器的for / break / else方案,以节省时间和LOC。 当前的示例是寻找候选者查找不完全合格的路径。 如果您希望看到原始上下文,请参阅原始问题

def match(path, actual):
    path = path.strip('/').split('/')
    actual = iter(actual.strip('/').split('/'))
    for pathitem in path:
        for item in actual:
            if pathitem == item:
                break
        else:
            return False
    return True

在此处使for / else如此出色的原因是避免杂耍布尔值的优雅。 如果没有else ,但希望达到相同的短路量,可以这样写:

def match(path, actual):
    path = path.strip('/').split('/')
    actual = iter(actual.strip('/').split('/'))
    failed = True
    for pathitem in path:
        failed = True
        for item in actual:
            if pathitem == item:
                failed = False
                break
        if failed:
            break
    return not failed

我认为使用else会使它更加优雅和明显。

循环的else子句的一个用例是跳出嵌套循环:

while True:
    for item in iterable:
        if condition:
            break
        suite
    else:
        continue
    break

它避免了重复条件:

while not condition:
    for item in iterable:
        if condition:
            break
        suite

干得好:

a = ('y','a','y')
for x in a:
  print x,
else:
  print '!'

这是为了守车。

编辑:

# What happens if we add the ! to a list?

def side_effect(your_list):
  your_list.extend('!')
  for x in your_list:
    print x,

claimant = ['A',' ','g','u','r','u']
side_effect(claimant)
print claimant[-1]

# oh no, claimant now ends with a '!'

编辑:

a = (("this","is"),("a","contrived","example"),("of","the","caboose","idiom"))
for b in a:
  for c in b:
    print c,
    if "is" == c:
      break
  else:
    print

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM