[英]More than one for-loop in a python while-loop
I'm a python/coding newbie and I'm trying to put a two for loops into a while loop?我是 python/编码新手,我正在尝试将两个 for 循环放入 while 循环中? Can I do this?我可以这样做吗? How can I print out the dictionary mydict to make sure I am doing this correctly?如何打印字典 mydict 以确保我正确执行此操作?
I'm stuck.我被困住了。
40 minutes later. 40分钟后。 Not stuck anymore.不再卡住了。 Thanks everyone!感谢大家!
def runloop():
while uid<uidend:
for row in soup.findAll('h1'):
try:
name = row.findAll(text = True)
name = ''.join(name)
name = name.encode('ascii','ignore')
name = name.strip()
mydict['Name'] = name
except Exception:
continue
for row in soup.findAll('div', {'class':'profile-row clearfix'}):
try:
field = row.find('div', {'class':'profile-row-header'}).findAll$
field = ''.join(field)
field = field.encode('ascii','ignore')
field = field.strip()
except Exception:
continue
try:
value = row.find('div', {'class':'profile-information'}).findAl$
value = ''.join(value)
value = value.encode('ascii','ignore')
value = value.strip()
return mydict
mydict[field] = value
print mydict
except Exception:
continue
uid = uid + 1
runloop()运行循环()
On nested loops:在嵌套循环上:
You can nest for and while loops very deeply before python will give you an error, but it's usually bad form to go more than 4 deep.你可以在 python 给你一个错误之前非常深地嵌套 for 和 while 循环,但它通常是 go 超过 4 深的错误形式。 Make another function if you find yourself needing to do a lot of nesting.如果您发现自己需要进行大量嵌套,请制作另一个 function。 Your use is fine though.不过你的使用很好。
Some problems with the code:代码的一些问题:
runloop()
to actually use the function.不确定您是否只是没有发布 function 调用,但您需要调用runloop()
才能实际使用 function。You can put as many loops within other loops as you'd like.您可以根据需要在其他循环中放置任意数量的循环。 These are called nested loops.这些称为嵌套循环。
Also, printing a dictionary is simple:此外,打印字典很简单:
mydict = {}
print mydict
You are not helping yourself by having these all over the place到处都是这些东西并没有帮助自己
except Exception:
continue
That basically says, "if anything goes wrong, carry one and don't tell me about it."这基本上是说,“如果有什么问题,随身携带,不要告诉我。”
Something like this lets you at least see the exception这样的事情至少可以让您看到异常
except Exception as e:
print e
continue
Is mydict
declared somewhere? mydict
是否在某处宣布? That could be your problem那可能是你的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.