现在的位置: 首页 > 综合 > 正文

python学习总结之数据结构

2013年02月08日 ⁄ 综合 ⁄ 共 2104字 ⁄ 字号 评论关闭

python中有三种内建的数据结构------列表,元组,字典

List:列表l是一组有序项目的数据结构,可增可减。表示方式:shoplist=['apple','banana','bango']

#!/usr/bin/python
#filename:using_list.py
shoplist=['apple','mango','carrot','banana']
print 'I have',len(shoplist),'items to purchase.'
print 'There 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 'Sort shopping list is', shoplist
print 'The first item I will buy is',shoplist[0]
olditem=shoplist[0]
del shoplist[0]
print 'I brought the', olditem
print 'my shopping list is now ', shoplist

结果显示:其中函数sort()排序作用,del删除的作用,append()增加的作用,基本上都是英语本身的意思。

[root@fsailing1 python]# python using_list.py
I have 4 items to purchase.
There 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 None
Sort shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']
The first item I will buy is apple
I brought the apple
my shopping list is now  ['banana', 'carrot', 'mango', 'rice']

元组:和列表十分相似,只不过元组和字符串一样是不可变的也就是说你不能修改元组:

zoo=('wolf','elephant','penguin'),zoo[2]表示元组中第三个项目

#!/usr/bin/python
#filename:print_tuple.py
age=27
name='chenbinghui'
print '%s is %d years old' % (name,age)
print 'why is %s playing with that python?' %name

结果显示

[root@fsailing1 python]# python using_tuple.py
chenbinghui is 27 years old
why is chenbinghui playing with that python?

字典:相当于我们说的键值对一样,一个键值对应一个值并且键是唯一的。字典是dict类的实例/对象

d={key1:value1,key2:value2}

#!/usr/bin/python
#filename:using_dict.py
ab={'chen':'chenbinghuilove@126.com','zhou':'zhouqian@126.com','zhao':'zhaogang@qq.com'}
print "chen's address is %s" %ab['chen']
# Adding a key/value pair
ab['xiaoxiao']='xiaoxiao@126.com'
#deleting a key/value pair
del ab['zhao']
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 'zhou' in ab:
        print "\nzhou's address is %s" %ab['zhou']

结果显示:可以看到添加的写法,和删除的写法,这里的item()方法也可以换成是has_key

[root@fsailing1 python]# python using_dict.py
chen's address is chenbinghuilove@126.com

There are 3 contacts in the address-book

contact chen at chenbinghuilove@126.com
contact xiaoxiao at xiaoxiao@126.com
contact zhou at zhouqian@126.com

zhou's address is zhouqian@126.com

抱歉!评论已关闭.