list是處理一組有序項(xiàng)目的數(shù)據(jù)結(jié)構(gòu),即你可以在一個列表中存儲一個 序列 的項(xiàng)目。假想你有
一個購物列表,上面記載著你要買的東西,你就容易理解列表了。只不過在你的購物表上,可
能每樣?xùn)|西都獨(dú)自占有一行,而在Python中,你在每個項(xiàng)目之間用逗號分割。
列表中的項(xiàng)目應(yīng)該包括在方括號中,這樣Python就知道你是在指明一個列表。一旦你創(chuàng)建了一
個列表,你可以添加、刪除或是搜索列表中的項(xiàng)目。由于你可以增加或刪除項(xiàng)目,我們說列表
是 可變的 數(shù)據(jù)類型,即這種類型是可以被改變的。
#!/usr/bin/python
# Filename: using_list.py
# This is my shopping list
shoplist = ['apple', 'mango', 'carrot', 'banana']
print 'I have', len(shoplist),'items to purchase.'
print 'These items are:', # Notice the comma at end of the line
for item in shoplist:
print item,
print '\nI also have to buy rice.'
shoplist.append('rice')
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 using_list.py
I have 4 items to purchase.
These items are: apple mango carrot banana
I also have to buy rice.
My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']
I will sort my list now
Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
The first item I will buy is apple
I bought the apple
My shopping list is now ['banana', 'carrot', 'mango', 'rice']
注意,我們在print語句的結(jié)尾使用了一個 逗號 來消除每個print語句自動打印的換行符。這樣
做有點(diǎn)難看,不過確實(shí)簡單有效。