Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1421329
  • 博文数量: 239
  • 博客积分: 5909
  • 博客等级: 大校
  • 技术积分: 2715
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-24 20:19
文章分类

全部博文(239)

文章存档

2014年(4)

2013年(22)

2012年(140)

2011年(14)

2010年(59)

我的朋友

分类: Python/Ruby

2010-10-18 13:22:15

1. None, Ture, False
2. list,如:a=[1,4,3,'sd',"dk"],内建函数总结如下:

>>>test=[1,2,"yes"]

>>>test.append(1) #追加到链尾
>>>test
[1, 2, 'yes', 1]

>>>test.extend([ 'no','maybe']) #追加一个列表
>>>test
[1, 2, 'yes', 1, 'no', 'maybe']

>>> test.insert(0,'never') #在位置0插入'never'
>>> test
['never', 1, 2, 'yes', 1, 'no', 'maybe']

>>> test.remove('no') #删除第一个值为"no"的元素,如果不存在会抛出异常
>>> test
['never', 1, 2, 'yes', 1, 'maybe']

>>> test.reverse() #反转序列
>>> test
['maybe', 1, 'yes', 2, 1, 'never']

>>> test.pop() #返回并删除位置为i的元素,i默认为最后一个元素
'never'
>>> test
['maybe', 1, 'yes', 2, 1]

>>> test.index('yes') #返回第一个值为'yes'的元素,不存在则抛出异常
2

>>> test.count(1) #返回1出现的次数
2

>>>test.sort() #排序
>>> test
[1, 1, 2, 'maybe', 'yes']


list片断:

>>> test=['never', 1, 2, 'yes', 1, 'no', 'maybe']

>>> test[0:3] #包括test[0],不包括test[3]
['never', 1, 2]

>>> test[0:6:2] #包括test[0],不包括test[6],而且步长为2
['never', 2, 1]

>>> test[:-1] #包括开始,不包括最后一个
['never', 1, 2, 'yes', 1, 'no']

>>> test[-3:] #抽取最后3个
[1, 'no', 'maybe']

>>>test[::-1] #倒序排列
['maybe', 'no', 1, 'yes', 2, 1, 'never']


for循环:

>>>freshfruit=[' banana ',' loganberry ']
>>>[weapon.strip() for weapon in freshfruit]
['banana', 'loganberry']

strip()是去除字符串两端多于空格,该句是去除序列中的所有字串两端多余的空格

3. 元组Triple
一旦初始化便不能更改的数据结构,速度比list快.没有内建的方法。可以实现简单的数据替换。

a=1
b=2
a,b=b,a


4. set
无序不重复的元素集.运算包括:-(差),|(并),&(交),^(并-交)

5.dict

字典:关键字为不可变类型,如字符串,整数,只包含不可变对象的元组. 列表等不可以作为关键字. 如果列表中存在关键字对,可以用dict()直接构造字典.

>>>tel={'jack':4098,'sape':4139}

>>>tel['guido']=4127

>>>tel
{'sape': 4139, 'jack': 4098, 'guido': 4127}

>>>tel['jack'] #如果jack不存在,会抛出KeyError
4098
>>>a.get("zsp",5000) #如果"zsp"为tel的键则返回其值,否则返回5000

>>>del tel['sape'] #删除键'sape'和其对应的值
>>>tel.keys() #复制一份键的副本,同理tel.items()为值的副本
['jack', 'guido']

>>>"jack" in tel #判断"jack"是否tel的键
True
>>>"zsp" not in tel
True

>>>for k,v in tel.iteritems():print k,v #同理tel.iterkeys()为键的迭代器,tel.itervalues()为值的迭代器
jack 4098
guido 4127

>>>tel.copy() #复制一份tel
{'jack': 4098, 'guido': 4127}

>>> tel.fromkeys([1,2],0) #从序列生成并返回一个字典,其值为第二个参数(默认为None),不改变当前字典
{1: 0, 2: 0}

>>>tel.popitem() #弹出一项
('jack', 4098)


阅读(943) | 评论(1) | 转发(0) |
0

上一篇:python基本语法

下一篇:Python基本函数(一)

给主人留下些什么吧!~~

chinaunix网友2010-10-18 16:45:52

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com