python学习总结之数据结构

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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值