大体上把Python中的数据类型分为如下几类:
Number(数字)         包括int,long,float,complex  
String(字符串)        例如:hello,"hello",hello  
List(列表)          例如:[1,2,3],[1,2,3,[1,2,3],4]  
Dictionary(字典)       例如:{1:"nihao",2:"hello"}  
Tuple(元组)          例如:(1,2,3,abc) 
Bool(布尔)          包括True、False  
由于Python中认为所有的东西都是对象,所以Python不用像其它一些高级语言那样主动声明一个变量的类型。
例如我要给一个变量i赋值100,python的实现 :
i=100
C#的实现:
int i = 100;
下面一一简单介绍这几种数据类型
数字类型
int和long
之所以要把int和long放在一起的原因是python3.x之后已经不区分int和long,统一用int。python2.x还是区分的。下面我以Python2.7为例:
>>> i = 10 >>> type(i) <type 'int'> >>> i=10000000000 >>> type(i) <type 'long'>
那么为什么10就是int,10000000000就是long呢,当然这就和int的最大值有关了,int类型的最大值为231-1,即2147483647,也可以用sys.maxint。
>>> 2**31-1 2147483647L >>> sys.maxint 2147483647
为什么用上面的方法求的值就是long型的呢(数字后面加‘L'表示是long型),因为2**31的值为2147483648,这个值是一个long型,用一个long型减去1,结果还是一个long,但实际上int型的最大值就是2147483647
>>> type(2147483647) <type 'int'> >>> type(2147483648) <type 'long'>
float类型
float类型和其它语言的float基本一致,浮点数,说白了,就是带小数点的数,精度与机器相关。例如:
>>> i = 10000.1212 >>> type(i) <type 'float'>
complex:复数类型,具体含义及用法可自行查看相关文档。
字符串类型
字符串的声明有三种方式:单引号、双引号和三引号(包括三个单引号或三个双引号)。例如:
>>> str1 = 'hello world' >>> str2 = "hello world" >>> str3 = '''hello world''' >>> str4 = """hello world""" >>> print str1 hello world >>> print str2 hello world >>> print str3 hello world >>> print str4 hello world
Python中的字符串有两种数据类型:str类型和unicode类型。str类型采用的ASCII编码,也就是说它无法表示中文。unicode类型采用unicode编码,能够表示任意字符,包括中文及其它语言。并且python中不存在像c语言中的char类型,就算是单个字符也是字符串类型。字符串默认采用的ASCII编码,如果要显示声明为unicode类型的话,需要在字符串前面加上'u'或者'U'。例如:
>>> str1 = "hello" >>> print str1 hello >>> str2 = u"中国" >>> print str2 中国
由于项目中经常出现对字符串的操作,而且由于字符串编码问题出现的问题很多,下面,来说一下关于字符串的编码问题。在与python打交道的过程中经常会碰到ASCII、Unicode和UTF-8三种编码。具体的介绍请参见这篇文章。我简单的理解就是,ASCII编码适用英文字符,Unicode适用于非英文字符(例如中文、韩文等),而utf-8则是一种储存和传送的格式,是对Uncode字符的再编码(以8位为单位编码)。例如:
u = u'汉' 
print repr(u) # u'u6c49' 
s = u.encode('UTF-8') 
print repr(s) # 'xe6xb1x89' 
u2 = s.decode('UTF-8') 
print repr(u2) # u'u6c49' 
解释:声明unicode字符串”汉“,它的unicode编码为”u6c49“,经过utf-8编码转换后,它的编码变成”xe6xb1x89“。
对于编码的经验总结:
1.在python文件头声明编码格式 ;
#-*- coding: utf-8 -*-  
2.将字符串统一声明为unicode类型,即在字符串前加u或者U;
3.对于文件读写的操作,建议适用codecs.open()代替内置的open(),遵循一个原则,用哪种格式写,就用哪种格式读;
假设在一个以ANSI格式保存的文本文件中有“中国汉字”几个字,如果直接用以下代码,并且要在GUI上或者在一个IDE中打印出来(例如在sublime text中,或者在pydev中打印),就会出现乱码或者异常,因为codecs会依据文本本身的编码格式读取内容:
f = codecs.open("d:/test.txt") 
content = f.read() 
f.close() 
print content 
改用如下方法即可(只对中文起作用):
# -*- coding: utf-8 -*- 
import codecs 
f = codecs.open("d:/test.txt") 
content = f.read() 
f.close() 
if isinstance(content,unicode): 
  print content.encode('utf-8') 
  print "utf-8" 
else: 
  print content.decode('gbk').encode('utf-8') 
列表类型
列表是一种可修改的集合类型,其元素可以是数字、string等基本类型,也可以是列表、元组、字典等集合对象,甚至可以是自定义的类型。其定义方式如下:
>>> nums = [1,2,3,4] >>> type(nums) <type 'list'> >>> print nums [1, 2, 3, 4] >>> strs = ["hello","world"] >>> print strs ['hello', 'world'] >>> lst = [1,"hello",False,nums,strs] >>> type(lst) <type 'list'> >>> print lst [1, 'hello', False, [1, 2, 3, 4], ['hello', 'world']]
用索引的方式访问列表元素,索引从0开始,支持负数索引,-1为最后一个.
>>> lst = [1,2,3,4,5] >>> print lst[0] 1 >>> print lst[-1] 5 >>> print lst[-2] 4
支持分片操作,可访问一个区间内的元素,支持不同的步长,可利用分片进行数据插入与复制操作
nums = [1,2,3,4,5] print nums[0:3] #[1, 2, 3] #前三个元素 print nums[3:] #[4, 5] #后两个元素 print nums[-3:] #[3, 4, 5] #后三个元素 不支持nums[-3:0] numsclone = nums[:] print numsclone #[1, 2, 3, 4, 5] 复制操作 print nums[0:4:2] #[1, 3] 步长为2 nums[3:3] = ["three","four"] #[1, 2, 3, 'three', 'four', 4, 5] 在3和4之间插入 nums[3:5] = [] #[1, 2, 3, 4, 5] 将第4和第5个元素替换为[] 即删除["three","four"]
支持加法和乘法操作
lst1 = ["hello","world"] lst2 = ['good','time'] print lst1+lst2 #['hello', 'world', 'good', 'time'] print lst1*5 #['hello', 'world', 'hello', 'world', 'hello', 'world', 'hello', 'world', 'hello', 'world']
列表所支持的方法,可以用如下方式查看列表支持的公共方法:
>>> [x for x in dir([]) if not x.startswith("__")] 
['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] 
def compare(x,y): 
  return 1 if x>y else -1 
#【append】 在列表末尾插入元素 
lst = [1,2,3,4,5] 
lst.append(6)  
print lst   #[1, 2, 3, 4, 5, 6] 
lst.append("hello") 
print lst   #[1, 2, 3, 4, 5, 6] 
#【pop】 删除一个元素,并返回此元素的值 支持索引 默认为最后一个 
x = lst.pop() 
print x,lst   #hello [1, 2, 3, 4, 5, 6] #默认删除最后一个元素 
x = lst.pop(0) 
print x,lst   #1 [2, 3, 4, 5, 6] 删除第一个元素 
#【count】 返回一个元素出现的次数 
print lst.count(2)  #1   
#【extend】 扩展列表 此方法与“+”操作的不同在于此方法改变原有列表,而“+”操作会产生一个新列表 
lstextend = ["hello","world"] 
lst.extend(lstextend) 
print lst      #[2, 3, 4, 5, 6, 'hello', 'world'] 在lst的基础上扩展了lstextend进来  
#【index】 返回某个值第一次出现的索引位置,如果未找到会抛出异常 
print lst.index("hello") #5   
#print lst.index("kitty") #ValueError: 'kitty' is not in list 出现异常 
#【remove】 移除列表中的某个元素,如果待移除的项不存在,会抛出异常 无返回值 
lst.remove("hello") 
print lst   #[2, 3, 4, 5, 6, 'world'] "hello" 被移除 
#lst.remove("kitty")     #ValueError: list.remove(x): x not in list 
#【reverse】 意为反转 没错 就是将列表元素倒序排列,无返回值 
print lst    #[2, 3, 4, 5, 6, 'world'] 
lst.reverse()  
print lst    #[2, 3, 4, 5, 6, 'world'] 
#【sort】 排序 
print lst  #由于上面的反转 目前排序为 ['world', 6, 5, 4, 3, 2] 
lst.sort()  
print lst  #排序后 [2, 3, 4, 5, 6, 'world'] 
nums = [10,5,4,2,3] 
print nums   #[10,5,4,2,3] 
nums.sort(compare) 
print nums   #[2, 3, 4, 5, 10] 
列表转换为迭代器。
所谓的迭代器就是具有next方法(这个方法在调用时不需要任何参数)的对象。在调用next方法时,迭代器会返回它的下一个值。如果next方法被调用,但迭代器没有值可以返回,就会引发一个StopIteration异常。迭代器相对于列表的优势在于,使用迭代器不必一次性将列表加入内存,而可以依次访问列表的数据。
依然用上面的方法查看迭代器的公共方法:
lst = [1,2,3,4,5] 
lstiter = iter(lst) 
print [x for x in dir(numiter) if not x.startswith("__")] 
>>>['next'] 
没错,只有next一个方法,对于一个迭代器,可以这样操作:
lst = [1,2,3,4,5] lstiter = iter(lst) for i in range(len(lst)): print lstiter.next() #依次打印 1 2 3 4 5
元组类型
元组类型和列表一样,也是一种序列,与列表不同的是,元组是不可修改的。元组的声明如下:
lst = (0,1,2,2,2) 
lst1=("hello",) 
lst2 = ("hello") 
print type(lst1)  #<type 'tuple'> 只有一个元素的情况下后面要加逗号 否则就是str类型 
print type(lst2)  #<type 'str'> 
字典类型
字典类型是一种键值对的集合,类似于C#中的Dictionary<object,object>或js中的json对象。其初始化方法如下:
dict1 = {} 
print type(dict1)   #<type 'dict'> 声明一个空字典 
dict2 = {"name":"kitty","age":18}  #直接声明字典类型 
dict3 = dict([("name","kitty"),("age",18)]) #利用dict函数将列表转换成字典 
dict4 = dict(name='kitty',age=18)      #利用dict函数通过关键字参数转换为字典 
dict5 = {}.fromkeys(["name","age"])   #利用fromkeys函数将key值列表生成字典,对应的值为None  {'age': None, 'name': None} 
字典基本的操作方法:
#【添加元素】  
dict1 = {} 
dict1["mykey"] = "hello world"   #直接给一个不存在的键值对赋值 即时添加新元素 
dict1[('my','key')] = "this key is a tuple"  #字典的键可以是任何一中不可变类型,例如数字、字符串、元组等 
#【键值对个数】 
print len(dict1) 
#【检查是否含有键】 
print "mykey" in dict1     #True 检查是否含有键为mykey的键值对 
print "hello" in dict1     #False 
#【删除】 
del dict1["mykey"]      #删除键为mykey的键值对 
继续利用上面的方法查看字典的所有公共方法:
>>> [x for x in dir({}) if not x.startswith("__")] 
['clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 
 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues'] 
 
dict.clear()                          删除字典中所有元素  
  
dict.copy()                          返回字典(浅复制)的一个副本  
  
dict.get(key,default=None)     对字典dict 中的键key,返回它对应的值value,如果字典中不存在此键,则返回default 的值(注意,参数default 的默认值为None)  
  
dict.has_key(key)                 如果键(key)在字典中存在,返回True,否则返回False. 在Python2.2版本引入in 和not in 后,此方法几乎已废弃不用了,但仍提供一个 可工作的接口。  
  
dict.items()                         返回一个包含字典中(键, 值)对元组的列表  
  
dict.keys()                          返回一个包含字典中键的列表  
  
dict.values()                        返回一个包含字典中所有值的列表  
  
dict.iter()                            方法iteritems(), iterkeys(), itervalues()与它们对应的非迭代方法一样,不同的是它们返回一个迭代器,而不是一个列表。  
  
dict.pop(key[, default])         和方法get()相似,如果字典中key 键存在,删除并返回dict[key],如果key 键不存在,且没有给出default 的值,引发KeyError 异常。  
  
dict.setdefault(key,default=None)  和方法set()相似,如果字典中不存在key 键,由dict[key]=default 为它赋值。  
  
dict.setdefault(key,default=None)   和方法set()相似,如果字典中不存在key 键,由dict[key]=default 为它赋值。  
布尔类型
布尔类型即True和False,和其它语言中的布尔类型基本一致。下面列出典型的布尔值
print bool(0)  #False 
print bool(1)  #True 
print bool(-1) #True 
print bool([]) #False 
print bool(()) #False 
print bool({}) #False 
print bool('') #False 
print bool(None) #False