gpt4 book ai didi

Python 在嵌套循环内继续,到达正确的嵌套级别

转载 作者:行者123 更新时间:2023-12-01 04:51:54 28 4
gpt4 key购买 nike

我正在做一些事情,需要在退出全部或设置某些变量然后开始循环之前通过几个级别检查是否满足条件。我的问题围绕如何从内部 for 循环跳回主 while 循环。

while True:
message = stomp.get
message = simplejson.loads(message.body)

if message[0]['fieldname1'] == False:
global ShutdownState
ShutdownState = True
break # Should leave the While loop all together

else:

for item in message[0]['fieldname2'][0]['fieldname2-1']

if item['fieldname2-1-1'] == True:
list1_new[len(list_new):] = [item['fieldname2-1-2']
list1-state = set(list1) == set(list1_new)

if list1-state == True:
continue # should reset the while loop

else:
list1 = list1_new # should print the new list1 and then reset the while loop
print list1
continue

最佳答案

尚不清楚示例代码是代表整个循环,还是仅代表循环的开始。如果这是整个事情,那么你可以通过很多方法来重组它。这是第一次尝试(请注意,代码中存在一些拼写错误(例如,list1-state 而不是 list1_state 等),因此我必须进行调整有些事情。您需要检查它是否仍然与您的原始代码匹配。(有关查找列表中第一个元素的实现以及一些替代方案的更多信息,请查看 Python: Find in list 。)

while True:
message = stomp.get
message = simplejson.loads(message.body)

# If the message doesn't match this criterion,
# we need to abort everything.
if not message[0]['fieldname1']:
global ShutdownState
ShutdownState = True
break

try:
# get the first item in message[0]['fieldname2'][0]['fieldname2-1']
# such item['fieldname2-1-1'] is true. Whether we
# find one and do this code, or don't and catch the
# StopIteration, we wrap back to the while loop.
item = next(x
for x in message[0]['fieldname2'][0]['fieldname2-1']
if item['fieldname2-1-1'])
list1_new[len(list_new),:] = item['fieldname2-1-2']
list1_state = (set(list1) == set(list1_new))

if not list1_state:
list1 = list1_new # should print the new list1 and then reset the while loop
print list1
except StopIteration:
# There was no such item.
pass

您也可以通过将其设置为 do-while 循环来清理它,但这不是主要因素。基于Emulate a do-while loop in Python? ,你可以这样做:

def get_message():
message = stomp.get
return simplejson.loads(message.body)

message = get_message()
while message[0]['fieldname1']:
try:
# get the first item in message[0]['fieldname2'][0]['fieldname2-1']
# such item['fieldname2-1-1'] is true. Whether we
# find one and do this code, or don't and catch the
# StopIteration, we wrap back to the while loop.
item = next(x
for x in message[0]['fieldname2'][0]['fieldname2-1']
if item['fieldname2-1-1'])
list1_new[len(list_new),:] = item['fieldname2-1-2']
list1_state = (set(list1) == set(list1_new))

if not list1_state:
list1 = list1_new # should print the new list1 and then reset the while loop
print list1
except StopIteration:
# There was no such item.
pass
message = get_message()

global ShutdownState
ShutdownState = True

关于Python 在嵌套循环内继续,到达正确的嵌套级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28248613/

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