3 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
您只是忘記使用新索引更新您的 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貢獻(xiàn)1788條經(jīng)驗(yàn) 獲得超4個(gè)贊
使用iteraor會(huì)更Pythonic?,而不是更新索引并根據(jù)它獲取新元素:
#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)
請(qǐng)注意,當(dāng)?shù)骱谋M時(shí),您需要小心(您還需要對(duì)索引進(jìn)行處理,以防它超過(guò)列表的大小......)

TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超6個(gè)贊
如果該代碼對(duì)您有意義,請(qǐng)使用它。
#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)
添加回答
舉報(bào)