2. # Filename: using_list.py
3.
4. # This is my shopping list
5. shoplist = ['apple', 'mango', 'carrot', 'banana']
6.
7. print 'I have', len(shoplist),'items to purchase.'
8.
9. print 'These items are:', # Notice the comma at end of the line
10. for item in shoplist:
11. print item,
12.
13. print '/nI also have to buy rice.'
14. shoplist.append('rice')
15. print 'My shopping list is now', shoplist
16.
17. print 'I will sort my list now'
18. shoplist.sort()
19. print 'Sorted shopping list is', shoplist
20.
21. print 'The first item I will buy is', shoplist[0]
22. olditem = shoplist[0]
23. del shoplist[0]
24. print 'I bought the', olditem
25. print 'My shopping list is now', shoplist
26.
输出
1. $ python using_list.py
2. I have 4 items to purchase.
3. These items are: apple mango carrot banana
4. I also have to buy rice.
5. My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
6. I will sort my list now
7. Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
8. The first item I will buy is apple
9. I bought the apple
10. My shopping list is now ['banana', 'carrot', 'mango', 'rice']
11.
它如何工作