为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

一只甜甜圈 2023-08-08 16:27:54
我需要更改循环外的参数并在满足特定条件后继续迭代。例如,我有披萨列表和字符串列表。我有在满足条件后应该切换的酱汁包列表。如果字符串中存在条件“sauce_error”,我需要从酱包列表中切换到另一个酱包,并使用下一个酱包继续迭代。#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    print(saucePack, pizza)  else:    print(saucePack, pizza)当“pizza”字符串中出现“sauce_error”时,应将酱包切换到列表中的下一个。期望的输出:sauce_pack1 pizza1sauce_pack1 pizza2sauce_pack2 pizza3_sauce_errorsauce_pack2 pizza4sauce_pack2 pizza5
查看完整描述

3 回答

?
12345678_0001

TA贡献1802条经验 获得超5个赞

您只是忘记使用新索引更新您的 saucePack:


#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

        saucePack = saucePacks[index]

        print(saucePack, pizza)

    else:

        print(saucePack, pizza)


查看完整回答
反对 回复 2023-08-08
?
尚方宝剑之说

TA贡献1788条经验 获得超4个赞

使用iteraor会更Pythonic ,而不是更新索引并根据它获取新元素:

#list of sauce packs

saucePacks = iter(['sauce_pack1', 'sauce_pack2', 'sauce_pack3', 'sauce_pack4'])

saucePack = next(saucePacks)


#list of pizzas

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


#iterating over strings

for pizza in pizzas:  

    if 'sauce_error' in pizza:

        saucePack = next(saucePacks)  # takes the next sauce from the list

    print(saucePack, pizza)

请注意,当迭代器耗尽时,您需要小心(您还需要对索引进行处理,以防它超过列表的大小......)


查看完整回答
反对 回复 2023-08-08
?
慕哥9229398

TA贡献1877条经验 获得超6个赞

如果该代码对您有意义,请使用它。


#list of sauce packs

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

index = 0


#list of pizzas

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


#iterating over strings

for 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)


查看完整回答
反对 回复 2023-08-08
  • 3 回答
  • 0 关注
  • 135 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信