gpt4 book ai didi

python 基本 while 循环

转载 作者:太空宇宙 更新时间:2023-11-04 07:48:00 25 4
gpt4 key购买 nike

我有另一个新手 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 中的有效语法。我知道我所拥有的会起作用,但是有更好的方法吗?谢谢。

最佳答案

简单计数器的“无限”特性具有一定的吸引力。但是,这也是有人通过欺骗具有数十亿个字段的表单来尝试拒绝服务攻击的机会。当您尝试处理数十亿个字段时,简单地对字段进行计数可能会使您的 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

关于python 基本 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2296803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com