gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 19:14:01 25 4
gpt4 key购买 nike

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

例如,我有披萨列表和字符串列表。我有在满足条件后应该切换的酱汁包列表。如果字符串中存在条件“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

最佳答案

您只是忘记使用新索引更新您的 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)

关于python - 满足条件后继续使用更改的参数进行迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63916977/

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