满足条件后继续使用更改的参数进行迭代

我需要更改循环外的参数并在满足特定条件后继续迭代。


例如,我有披萨列表和字符串列表。我有在满足条件后应该切换的酱汁包列表。如果字符串中存在条件“sauce_error”,我需要从酱包列表中切换到另一个酱包,并使用下一个酱包继续迭代。


#list of sauce packs

saucePacks = ['sauce_pack1', 'sauce_pack2', 'sauce_pack3', 'sauce_pack4']

index = 0

saucePack = saucePacks[index]


#list of pizzas

pizzas = ['pizza1', 'pizza2', 'pizza3_sauce_error', 'pizza4', 'pizza5']


#iterating over strings

for pizza in pizzas:  

  if 'sauce_error' in pizza:

    index = index+1 #need to switch sauce pack if substring in string

    print(saucePack, pizza)

  else:

    print(saucePack, pizza)

当“pizza”字符串中出现“sauce_error”时,应将酱包切换到列表中的下一个。


期望的输出:


sauce_pack1 pizza1

sauce_pack1 pizza2

sauce_pack2 pizza3_sauce_error

sauce_pack2 pizza4

sauce_pack2 pizza5


一只甜甜圈
浏览 136回答 3
3回答

12345678_0001

您只是忘记使用新索引更新您的 saucePack:#list of sauce packssaucePacks = ['sauce_pack1', 'sauce_pack2', 'sauce_pack3', 'sauce_pack4']index = 0saucePack = saucePacks[index]#list of pizzaspizzas = ['pizza1', 'pizza2', 'pizza3_sauce_error', 'pizza4', 'pizza5']#iterating over stringsfor pizza in pizzas:      if 'sauce_error' in pizza:        index = index+1 #need to switch sauce pack if substring in string        saucePack = saucePacks[index]        print(saucePack, pizza)    else:        print(saucePack, pizza)

尚方宝剑之说

使用iteraor会更Pythonic ,而不是更新索引并根据它获取新元素:#list of sauce packssaucePacks = iter(['sauce_pack1', 'sauce_pack2', 'sauce_pack3', 'sauce_pack4'])saucePack = next(saucePacks)#list of pizzaspizzas = ['pizza1', 'pizza2', 'pizza3_sauce_error', 'pizza4', 'pizza5']#iterating over stringsfor pizza in pizzas:      if 'sauce_error' in pizza:        saucePack = next(saucePacks)  # takes the next sauce from the list    print(saucePack, pizza)请注意,当迭代器耗尽时,您需要小心(您还需要对索引进行处理,以防它超过列表的大小......)

慕哥9229398

如果该代码对您有意义,请使用它。#list of sauce packssaucePacks = ['sauce_pack1', 'sauce_pack2', 'sauce_pack3', 'sauce_pack4']index = 0#list of pizzaspizzas = ['pizza1', 'pizza2', 'pizza3_sauce_error', 'pizza4', 'pizza5']#iterating over stringsfor pizza in pizzas:    if 'sauce_error' in pizza:    index += 1 #need to switch sauce pack if substring in string    print(saucePacks[index], pizza)  else:    print(saucePacks[index], pizza)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python