第九章 数据结构
Python中内建三种数据结构:
列表 方括号中逗号隔开的项目,列表是可变的数据类型
元组 圆括号中逗号隔开的项目,元组的值不会改变
字典
- #!/usr/bin/python
- #Filename using_list.py
- 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 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', 'mango', 'carrot', 'banana', 'rice']
The first item I will buy is apple
I bought the apple
My shopping list is now ['mango', 'carrot', 'banana', 'rice']
###print 语句结尾使用一个逗号来消除换行符
- #!/usr/bin/python
- #Filename using_tuple.py
- zoo = ('wolf', 'elephant', 'penguin')
- print 'Number of animals in the zoo is', len(zoo)
- new_zoo = ('mokey', 'dolphin', zoo)
- print 'Number of animals in the new zoo is', len(new_zoo)
- print 'All animals in new zoo are', new_zoo
- print 'Animals brought from old zoo are', new_zoo[2]
- print 'Last animal brought from old zoo is', new_zoo[2][2]
$python using_tule.py
Number of animals in the zoo is 3
Number of animals in the new zoo is 3
All animals is new zoo are ('mokey', 'dolphin', ('wolf', 'elephant', 'penguin'))
Animals brought from old zoo are ('wolf', 'elephant', 'penguin')
Last animal brought from old zoo is penguin
###含有0个或1个项目的元组:
myempty = ()
singleton = (2, ) #必须在单一的项目后跟一个逗号,区分元组和表达式中一个带圆括号的对象
- #!/usr/bin/python
- #Filename print_tuple.py
- age = 22
- name = 'Swaroop'
- print '%s is %d years old' % (name, age)
- print 'Why is %s playing with that python?' % name
$python print_tuple.py
Swaroop is 22 years old
Why is Swaroop playing with that python?
- #!/usr/bin/python
- #Filename using_dict.py
- #'ab' is short for 'a'ddress'b'ook
- ab = { 'Swaroop' : '[email protected]',
- 'Larry' : '[email protected]',
- 'Matsumoto' : '[email protected]',
- 'Spammer' : '[email protected]'
- }
- print "Swarrop's address is %s" % ab['Swaroop']
- #Adding a key/value pair
- ab['Guido'] = '[email protected]'
- #Deleting a key/value pair
- del ab['Spammer']
- print '\nThere are %d contacts in the address-book\n' % len(ab)
- for name, address in ab.items():
- print 'Contact %s at %s' % (name, address)
- if 'Guido' in ab: # OR ab.has_key('Guido')
- print "\nGuido's address is %s" % ab['Guido']