3 回答
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)
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)
请注意,当迭代器耗尽时,您需要小心(您还需要对索引进行处理,以防它超过列表的大小......)
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)
添加回答
举报