Pythonic在for循环中使用'else'的方法

时间:2009-03-26 13:22:32

标签: for-loop python

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

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

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

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

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

7 个答案:

答案 0 :(得分:15)

什么可能比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)

答案 1 :(得分:6)

如果你有for循环,你真的没有任何条件声明。因此,如果您想中止,那么休息是您的选择,然后可以完美地处理您不满意的情况。

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

答案 2 :(得分:4)

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

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中非0值为真的事实来做(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是一个可能的除数值则不会起作用......

答案 3 :(得分:3)

不使用breakelse块对forwhile语句没有任何好处。以下两个例子是等效的:

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

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

elseforwhile一起使用的唯一原因是,如果循环正常终止,则在循环后执行某些操作,这意味着没有明确的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

答案 4 :(得分:2)

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

break and continue Statements, and else Clauses on Loops

  

循环语句可能有其他内容   条款;它在循环时执行   通过筋疲力尽终止   列表(with for)或何时条件   变得虚假(同时),但不是   当循环终止时   声明

答案 5 :(得分:0)

我被介绍了一个很好的习语,你可以使用for / break / else方案和迭代器来节省时间和LOC。手头的例子是搜索不完全合格路径的候选者。如果您想了解原始背景,请参阅the original question

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的使用使它更优雅,更明显。

答案 6 :(得分:-1)

你走了:

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