shoplist = ['apple', 'mango', 'carrot', 'banana'] #定义一个列表 print 'I have', len(shoplist),'items to purchase' #计算列表长度 print 'These items are:', #遍历列表 for item in shoplist: print item, print '\nI also to buy rice' shoplist.append('rice') #列表当中添加item print 'My shopping list is now',shoplist print 'I will sort my list now' shoplist.sort() #列表进行排序 print 'Sorted shopping list is ',shoplist print 'The first item I will buy is',shoplist[0] #访问单个列表元素 olditem = shoplist[0] del shoplist[0] #删除列表元素 print 'I bought the',olditem print 'My shopping list is now',shoplist
本文介绍了一个简单的Python脚本,展示了如何使用列表存储购物清单,包括计算列表长度、遍历打印列表项、添加新项、排序列表以及删除项的过程。

被折叠的 条评论
为什么被折叠?



