早教吧 育儿知识 作业答案 考试题库 百科 知识分享

pythonfor循环问题shoplist=['apple','mango','carrot','banana']print'ihave',len(shoplist)+1,'itemtobuy'print'theitemare:',shoplistprint('\nihavetobuyrice.')shoplist.append('rice')print'myshoplistisnow',shoplistprint('iwillsort

题目详情
python for循环问题
shoplist = ['apple','mango','carrot','banana']
print 'i have',len(shoplist)+1,'item to buy'
print 'the item are:',shoplist
print ('\n i have to buy rice .')
shoplist.append('rice')
print'my shoplist is now',shoplist
print('i will sort my shoplist')
shoplist.sort()
print'sorted list is ',shoplist
count = 0
sz=['first','second','third','fouth','fifth']
for item in shoplist:
print'the ',sz[count],' item i will buy is',shoplist[0]
print('i bought the'),shoplist[0]
del shoplist[0]
print('my shoplist is now,'),shoplist
count=count+1
为什么结果只能出来我要买的东西只显示到third,后面的mango和rice不会出来,仍然留在shoplist里面求大神解答
▼优质解答
答案和解析
你用for循环遍历列表的同时还使用了del 改变列表长度,这是忌讳.
下面是更改后的代码,你可以对比看看.

shoplist = ['apple', 'mango', 'carrot', 'banana']
print 'I have', len(shoplist) + 1, 'items to buy'
print 'They are:', shoplist
print ('\nI have to buy rice.')
shoplist.append('rice')
print 'My shoplist is now', shoplist
print('I will sort my shoplist')
shoplist.sort()
print 'Sorted list is', shoplist

count = 0
sz = ['first', 'second', 'third', 'fouth', 'fifth']
for item in shoplist:
    print 'The', sz[count], 'item I will buy is', shoplist[count]
    print 'I bought the', shoplist[count]
    print('My shoplist is now'), shoplist[count+1:]
    count += 1
主要修改了for循环里面的相关语句.