Python:嵌套for循环或“下一个”声明 [英] Python: Nested for loops or "next" statement

查看:152
本文介绍了Python:嵌套for循环或“下一个”声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  dict = {$ p> 

我是一名新手爱好者,并且在编写python时嵌套for循环。 b $ b key1:{subkey / value1:value2}
...
keyn:{subkeyn / valuen:valuen + 1}
}

字典:
为子键/键值:
做它

我知道一个下一个关键字可以在一行中完成相同的目标(我问了一个关于如何使用它的问题,但是我不太明白)。

所以对我来说,嵌套for循环更可读。那么为什么人们用下一个呢?我在某处读到Python是一种动态类型和解释的语言,因为它们都会连续字符串和总和数字,它必须检查每个循环迭代的变量类型,以便知道操作符是什么等。使用next这在某种程度上,加快执行或者只是一个风格/偏好的问题?

解决方案

next 对于在必要时推进迭代器非常宝贵, 没有提前控制循环的显式。例如,如果你想要S中的第一个项目大于100,那么 next(x对于S中的x如果x> 100)将会给你,没有麻烦,没有大惊小怪,没有不必要的工作(因为一旦一个合适的 x 所在的地方,所有东西都会终止) - 并且你得到一个异常( StopIteration )如果意外地没有 x 符合条件。如果预期不匹配,并且在这种情况下你想要 None ,那么 next((x对于S中的x,如果x> 100) )将提供。为了这个特定的目的,如果 next 实际上被命名为 first ,那么对你来说可能会更清楚一些,更普遍的用途。例如,考虑合并多个序列的任务(例如,排序序列的联合或交集 - 即排序文件,其中项目是线)。同样, next 就是医生的命令,因为没有一个序列可以通过控制A

来控制循环。所以,假定为了简单起见,不存在重复项(如果需要,不难放松的条件),在由<$ c控制的列表中保持对(currentitem,itsfile) $ c> heapq ,并且合并变得很容易...但是只能感谢下一个的魔术来推进正确的 strong>文件一旦它的项目已被使用,并只有该文件。

  import heapq 

def合并(* theopentextfiles):
theheap = []
for theopentextfiles中的afile:
theitem = next(afile,'')
如果theitem:theheap.append((theitem, afile)
heapq.heapify(theheap)
whileheap:
theitem,afile = heapq.heappop(theheap)
yielf theitem
theitem = next(afile, '')
如果theitem:heapq.heappush(theheap,(theitem,afile))

只要 在这个优雅的地方做任何事情,而不用 next ...! - >



一个人可以继续很长时间,但是这两个用例在一个地方推进一个迭代器(而不是让它控制循环的整个)和从迭代器帐户获取第一个项目,用于 next 的最重要用途。


I'm a rookie hobbyist and I nest for loops when I write python, like so:

dict = {
    key1: {subkey/value1: value2} 
    ... 
    keyn: {subkeyn/valuen: valuen+1}
    }

for key in dict:
    for subkey/value in key:
       do it to it

I'm aware of a "next" keyword that would accomplish the same goal in one line (I asked a question about how to use it but I didn't quite understand it).

So to me, a nested for loop is much more readable. Why, then do people use "next"? I read somewhere that Python is a dynamically-typed and interpreted language and because + both concontinates strings and sums numbers, that it must check variable types for each loop iteration in order to know what the operators are, etc. Does using "next" prevent this in some way, speeding up the execution or is it just a matter of style/preference?

解决方案

next is precious to advance an iterator when necessary, without that advancement controlling an explicit for loop. For example, if you want "the first item in S that's greater than 100", next(x for x in S if x > 100) will give it to you, no muss, no fuss, no unneeded work (as everything terminates as soon as a suitable x is located) -- and you get an exception (StopIteration) if unexpectedly no x matches the condition. If a no-match is expected and you want None in that case, next((x for x in S if x > 100), None) will deliver that. For this specific purpose, it might be clearer to you if next was actually named first, but that would betray its much more general use.

Consider, for example, the task of merging multiple sequences (e.g., a union or intersection of sorted sequences -- say, sorted files, where the items are lines). Again, next is just what the doctor ordered, because none of the sequences can dominate over the others by controlling A "main for loop". So, assuming for simplicity no duplicates can exist (a condition that's not hard to relax if needed), you keep pairs (currentitem, itsfile) in a list controlled by heapq, and the merging becomes easy... but only thanks to the magic of next to advance the correct file once its item has been used, and that file only.

import heapq

def merge(*theopentextfiles):
    theheap = []
    for afile in theopentextfiles:
        theitem = next(afile, '')
        if theitem: theheap.append((theitem, afile))
    heapq.heapify(theheap)
    while theheap:
        theitem, afile = heapq.heappop(theheap)
        yielf theitem
        theitem = next(afile, '')
        if theitem: heapq.heappush(theheap, (theitem, afile))

Just try to do anything anywhere this elegant without next...!-)

One could go on for a long time, but the two use cases "advance an iterator by one place (without letting it control a whole for loop)" and "get just the first item from an iterator" account for most important uses of next.

这篇关于Python:嵌套for循环或“下一个”声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆