python基本while循环

时间:2010-02-19 14:03:29

标签: python while-loop

我有另一个新手Python问题。我有一段代码,我有一种感觉并不是像pythonic那样写的:

    rowindex = 0
    while params.getfirst('myfield'+rowindex):
        myid = params.getfirst('myfield'+rowindex)
        # do stuff with myid
        rowindex+=1

此脚本的输入是一个HTML页面,可以包含任意数量的名为“myfield#”的输入字段,其中#从0开始并按顺序增加。在Perl中,我会做更多这样的事情:

    rowindex = 0
    while myid =  params.getfirst('myfield'+rowindex):
        #do stuff with myid
        rowindex+=1

但这不是Python中的有效语法。我知道我的工作会有什么用,但是有更好的方法吗?谢谢。

4 个答案:

答案 0 :(得分:5)

简单计数器的“无界”性质具有一定的吸引力。但是,这也是某人通过欺骗具有数十亿字段的表单来尝试拒绝服务攻击的机会。当您尝试处理这些数十亿个字段时,只需计算字段就可以阻止您的Web服务器。

由于Python会自动转换为long,因此通常的20亿整数溢出不适用。有人可以用数十亿的田地来惩罚你的网站。

for i in range(1024): # some sensible upper limit, beyond which the input is suspicious
    myid= params.getfirst("myfield%d" % i)
    if not myid: break
        # do stuff with myid

答案 1 :(得分:2)

我想我会制作一个小型生成器来完全封装循环逻辑:

import itertools

def genit(params):
  for rowindex in itertools.count():
    theid = params.getfirst('myfield%s' % rowindex)
    if not theid: break
    yield theid

这样可以在主流程中更清晰地看到应用程序(“业务”)逻辑:

for myid in genit(params):
    dosomething_with(myid)

尤其如果dosomething_with是内联的。生成器实际上是“猫的睡衣”,可以将丰富/复杂的循环逻辑与应用程序/业务逻辑完全分开。

如果由于某些特殊原因我渴望在这种特殊情况下将它们合并,我仍然会避免使用低抽象rowindex = 0 / while / rowindex += 1代码来支持{我认为{1}}更清晰,更清晰,更简洁。这个整体框架还可以更容易地在限制循环之间切换,如在接受的答案中,如果您决定这样做,并且具有无界循环,就像在原始问题中一样 - 只需将for rowindex in itertools.count():更改为/来自itertools.count()

答案 2 :(得分:1)

你可以这样做。我认为这更“灵活”,因为我可以在while循环中尽可能多地提供我想要的任何条件。但话说回来,有人会说它的个人品味。

rowindex = 0
while 1:
    myid = params.getfirst('myfield'+rowindex)
    if not myid:  #or check for length of 0 , etc, then break
       break
    rowindex+=1

答案 3 :(得分:-1)

尝试执行此操作

While 1:

    codehere