樣本1:LIST
取得list長度len(list),向list追加元素list.append(),list排序list.sort(),刪除list元素 del list[index]
代碼
#!/usr/bin/python
#filename:list.py
#This is my shopping list
shoplist = ['apple','mango','carrot','banana']
print '\nI have',
len(shoplist),'items to purchase:'
for item in
shoplist:
print item
print '\nAdd rice to the store: append()'
shoplist.append('rice')
print '\t ',shoplist
print '\nSORT the store: sort()\t'
shoplist.sort()
print '\t',shoplist
print '\nDEL item 0, the resule: del'
del shoplist[0]
print '\t',shoplist,'\n\n'
樣本2:tuple(元組)
列表中的列表不會丟失它的身份;可以認為列表中可儲存列表,整個列表作為一個元素對待;可以索引到列表後再繼續索引列表內的資料;注意最後萬用字元的用法: print '%s is %d years old' % (name, age)
print 'Why is %s playing with that python?' % name
代碼
#!/usr/bin/python
#filename:tuple.py
zoo = ['wolf','elephant','penguin']
new_zoo = ('monkey','dolphin',zoo)
print 'The OLD zoo had',len(zoo),'annimals:'
print '\t',zoo
print '\nThe NEW zoo have',len(new_zoo),'annimals:'
print '\t',new_zoo
print'\nAnimals brought from OLD zone are:',new_zoo[2] #zoo,the index is 2
print'Last animal brought from OLD zoo is: %s\n'%new_zoo[2][2]#zoo[2]
#--==------------ the output is -----------------==--
#phoenix@debian:~/py$ python tuple.py
#The OLD zoo had 3 annimals:
# ['wolf', 'elephant', 'penguin']
#The NEW zoo have 3 annimals:
# ('monkey', 'dolphin', ['wolf', 'elephant', 'penguin'])
#Animals brought from OLD zone are: ['wolf', 'elephant', 'penguin']
#Last animal brought from OLD zoo is: penguin