python中的数据结构

python中的数据结构

列表

list是处理一组有序项目的数据结构,即你可以在一个列表中存储一个 序列 的项目。假想你有一个购物列表,上面记载着你要买的东西,你就容易理解列表了。只不过在你的购物表上,可能每样东西都独自占有一行,而在Python中,你在每个项目之间用逗号分割。
列表中的项目应该包括在方括号中,这样Python就知道你是在指明一个列表。一旦你创建了一个列表,你可以添加、删除或是搜索列表中的项目。由于你可以增加或删除项目,我们说列表是 可变的 数据类型,即这种类型是可以被改变的。

# -*- coding: cp936 -*-
shoplist = ['mylove','for','isyou','fjeie'];
#声明列表
print shoplist;
for item in shoplist:
    print item;
 #遍历列表
print 'I alse have to buy rice';
shoplist.append('rice');
#向列表中添加元素
print 'my shoplist is now:',shoplist;

print 'shoplist is sorted:';
shoplist.sort();
#按照字母的顺序排序
print shoplist;

print shoplist[0];
#按序列对列表取元素
print shoplist[0][0];  
#提取出列表中的第一个元素之后,然后提取出第一个元素的第一的字母

del shoplist[0]  #删除列表中的第一个元素
print shoplist

元组

元组和列表十分类似,只不过元组和字符串一样是不可变的,即你不能修改元组。元组通过圆括号中用逗号分割的项目定义。元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用的元组的值不会改变。

# -*- coding: UTF-8 -*-
zoo=('my','second','third');
print 'the lenth of zoo is:',len(zoo);

shoplist = ['first','second','third'];
print len(shoplist);
#可以使用len来求元组和列表的长度

newzoo = ('mylove',zoo);
print newzoo #('mylove', ('my', 'second', 'third'))
print newzoo[1] #('my', 'second', 'third')
print newzoo[1][1]; #


newshoplist = ['list',zoo];
print newshoplist;

age = 11;
name = 'husan';

print (age,name);

字典

# -*- coding: UTF-8 -*-
dist = {
       'name':'huanglongji',
       'age' : 11,
    }
#声明字典
print dist;
dist['age'] = 123;
#内容修改
print dist;

del dist['name'];
print dist;
#删除字典中的元素
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值