shopping_food = ['bread', 'milk', 'apples', 'bananas']
#the initial list
print('\nHere is the list of grocey items I need:')
for food in shopping_food:
print(food)
add_items = int(input('\nHow many items do you want to add the list? '))
#How much food do we add
items_add = add_items + 1
for items in range(1,items_add):
shopping_food.append(input('Please enter item #%d: ' %items))
#the final list
numbers = int(len(shopping_food))
print('\nThe shopping list now has %d items:' %numbers)
for food in shopping_food:
print(food)
# epilogue
print('\nYou can now use this list to go shopping!')
for items in shopping_food:
shopping_food.remove(input('Type the name of the next item you want to remove: '))
choice = input('OK I have remove that item. Do you want to see the items remaining in the list? (Y/N)')
if choice == 'Y':
print('The remaining items on the list are: ')
for food in shopping_food:
print(food)
else:
print()
if int(len(shopping_food)) == 0:
print('You have now finished shopping!')
麻烦贴一下源代码方便调试
一般不推荐在遍历列表时做添加或者删除操作
移除了一个行之后其后面行的索引值都会减一,表格长度也会减一。
比如一开始循环索引值是0,移除了索引值是0的行之后,原来索引值为1的行的索引值减一变成0。原来索引值为2的行的索引值减一变成1。
下一次循环索引加1。移除索引值是1的行(原来索引值为2的行),原来索引值为1的行就被跳过了。
所以在移除操作时要倒着循环
你这运行结果哪里有问题?