shopping_cart = [['tooth paste', 'q-tips', 'milk],['milk', 'candy', 'apples'],['planner', 'pencils', 'q-tips']]
for x in shopping_cart: #this is the overall list
for i in shopping_cart: #This is the 3 inner lists?
if shopping_cart[0:2] != 'milk': # this should check for milk in list
shopping_cart.append('milk') # this should append milk to the end of the list if milk isnt in yet
由于您还没有提到您的预期输出,我假设这就是您想要的。
shopping_cart = [['tooth paste', 'q-tips', 'milk'],['milk', 'candy', 'apples'],
['planner', 'pencils', 'q-tips']]
for x in shopping_cart:
if 'milk' not in x:
x.append('milk')
print shopping_cart
输出:-
[['tooth paste', 'q-tips', 'milk'], ['milk', 'candy', 'apples'], ['planner', 'pencils', 'q-tips', 'milk']]