Python中的几种数据类型

大体上把Python中的数据类型分为如下几类:

 

  1. Number(数字)                  包括int,long,float,complex   
  2. String(字符串)                例如:hello,"hello",hello   
  3. List(列表)                    例如:[1,2,3],[1,2,3,[1,2,3],4]   
  4. Dictionary(字典)              例如:{1:"nihao",2:"hello"}   
  5. Tuple(元组)                   例如:(1,2,3,abc)  
  6. Bool(布尔)                    包括True、False   

由于Python中认为所有的东西都是对象,所以Python不用像其它一些高级语言那样主动声明一个变量的类型。

例如我要给一个变量i赋值100,python的实现 :

  1. i=100  

C#的实现:

  1. int i = 100;  

 

下面一一简单介绍这几种数据类型

 

数字类型

int和long

之所以要把int和long放在一起的原因是python3.x之后已经不区分int和long,统一用int。python2.x还是区分的。下面我以Python2.7为例:

  1. >>> i = 10  
  2. >>> type(i)  
  3. <type 'int'>  
  4.   
  5. >>> i=10000000000  
  6. >>> type(i)  
  7. <type 'long'>  

那么为什么10就是int,10000000000就是long呢,当然这就和int的最大值有关了,int类型的最大值为231-1,即2147483647,也可以用sys.maxint。

  1. >>> 2**31-1  
  2. 2147483647L  
  3. >>> sys.maxint  
  4. 2147483647  

为什么用上面的方法求的值就是long型的呢(数字后面加‘L’表示是long型),因为2**31的值为2147483648,这个值是一个long型,用一个long型减去1,结果还是一个long,但实际上int型的最大值就是2147483647

  1. >>> type(2147483647)  
  2. <type 'int'>  
  3. >>> type(2147483648)  
  4. <type 'long'>  

 

float类型

float类型和其它语言的float基本一致,浮点数,说白了,就是带小数点的数,精度与机器相关。例如:

  1. >>> i = 10000.1212  
  2. >>> type(i)  
  3. <type 'float'>  

 

complex:复数类型,具体含义及用法可自行查看相关文档。

 

字符串类型

字符串的声明有三种方式:单引号、双引号和三引号(包括三个单引号或三个双引号)。例如:

  1. >>> str1 = 'hello world'  
  2. >>> str2 = "hello world"  
  3. >>> str3 = '''hello world'''  
  4. >>> str4 = """hello world"""  
  5. >>> print str1  
  6. hello world  
  7. >>> print str2  
  8. hello world  
  9. >>> print str3  
  10. hello world  
  11. >>> print str4  
  12. hello world  

Python中的字符串有两种数据类型:str类型和unicode类型。str类型采用的ASCII编码,也就是说它无法表示中文。unicode类型采用unicode编码,能够表示任意字符,包括中文及其它语言。并且python中不存在像c语言中的char类型,就算是单个字符也是字符串类型。字符串默认采用的ASCII编码,如果要显示声明为unicode类型的话,需要在字符串前面加上'u'或者'U'。例如:

  1. >>> str1 = "hello"  
  2. >>> print str1  
  3. hello  
  4. >>> str2 = u"中国"  
  5. >>> print str2  
  6. 中国  

由于项目中经常出现对字符串的操作,而且由于字符串编码问题出现的问题很多,下面,来说一下关于字符串的编码问题。在与python打交道的过程中经常会碰到ASCII、Unicode和UTF-8三种编码。具体的介绍请参见这篇文章。我简单的理解就是,ASCII编码适用英文字符,Unicode适用于非英文字符(例如中文、韩文等),而utf-8则是一种储存和传送的格式,是对Uncode字符的再编码(以8位为单位编码)。例如:

  1. u = u'汉'  
  2. print repr(u) # u'\u6c49'  
  3. s = u.encode('UTF-8')  
  4. print repr(s) # '\xe6\xb1\x89'  
  5. u2 = s.decode('UTF-8')  
  6. print repr(u2) # u'\u6c49'  

解释:声明unicode字符串”汉“,它的unicode编码为”\u6c49“,经过utf-8编码转换后,它的编码变成”\xe6\xb1\x89“。

 

对于编码的经验总结:

1.在python文件头声明编码格式 ;

  1. #-*- coding: utf-8 -*-  

2.将字符串统一声明为unicode类型,即在字符串前加u或者U;

3.对于文件读写的操作,建议适用codecs.open()代替内置的open(),遵循一个原则,用哪种格式写,就用哪种格式读;

假设在一个以ANSI格式保存的文本文件中有“中国汉字”几个字,如果直接用以下代码,并且要在GUI上或者在一个IDE中打印出来(例如在sublime text中,或者在pydev中打印),就会出现乱码或者异常,因为codecs会依据文本本身的编码格式读取内容:

  1. f = codecs.open("d:/test.txt")  
  2. content = f.read()  
  3. f.close()  
  4. print content  

改用如下方法即可(只对中文起作用):

  1. # -*- coding: utf-8 -*-  
  2.   
  3. import codecs  
  4.   
  5. f = codecs.open("d:/test.txt")  
  6. content = f.read()  
  7. f.close()  
  8.   
  9. if isinstance(content,unicode):  
  10.     print content.encode('utf-8')  
  11.     print "utf-8"  
  12. else:  
  13.     print content.decode('gbk').encode('utf-8')  
 

列表类型

列表是一种可修改的集合类型,其元素可以是数字、string等基本类型,也可以是列表、元组、字典等集合对象,甚至可以是自定义的类型。其定义方式如下

  1. >>> nums = [1,2,3,4]  
  2. >>> type(nums)  
  3. <type 'list'>  
  4. >>> print nums  
  5. [1234]  
  6. >>> strs = ["hello","world"]  
  7. >>> print strs  
  8. ['hello''world']  
  9. >>> lst = [1,"hello",False,nums,strs]  
  10. >>> type(lst)  
  11. <type 'list'>  
  12. >>> print lst  
  13. [1'hello'False, [1234], ['hello''world']]  

 

用索引的方式访问列表元素,索引从0开始,支持负数索引,-1为最后一个.

  1. >>> lst = [1,2,3,4,5]  
  2. >>> print lst[0]  
  3. 1  
  4. >>> print lst[-1]  
  5. 5  
  6. >>> print lst[-2]  
  7. 4  

支持分片操作,可访问一个区间内的元素,支持不同的步长,可利用分片进行数据插入与复制操作

  1. nums = [1,2,3,4,5]  
  2. print nums[0:3]  #[1, 2, 3] #前三个元素  
  3.   
  4. print nums[3:]   #[4, 5]    #后两个元素  
  5.   
  6. print nums[-3:]  #[3, 4, 5] #后三个元素 不支持nums[-3:0]  
  7.   
  8. numsclone = nums[:]    
  9.   
  10. print numsclone    #[1, 2, 3, 4, 5]  复制操作  
  11.   
  12. print nums[0:4:2]   #[1, 3]    步长为2  
  13.   
  14. nums[3:3] = ["three","four"]   #[1, 2, 3, 'three', 'four', 4, 5]  在3和4之间插入  
  15.   
  16. nums[3:5] = []    #[1, 2, 3, 4, 5] 将第4和第5个元素替换为[] 即删除["three","four"]  

支持加法和乘法操作

  1. lst1 = ["hello","world"]  
  2. lst2 = ['good','time']  
  3. print lst1+lst2  #['hello', 'world', 'good', 'time']  
  4.   
  5. print lst1*5  #['hello', 'world', 'hello', 'world', 'hello', 'world', 'hello', 'world', 'hello', 'world']  

列表所支持的方法,可以用如下方式查看列表支持的公共方法:

  1. >>> [x for x in dir([]) if not x.startswith("__")]  
  2. ['append''count''extend''index''insert''pop''remove''reverse''sort']  
  1. def compare(x,y):  
  2.     return 1 if x>y else -1  
  3.   
  4.   
  5. #【append】  在列表末尾插入元素  
  6. lst = [1,2,3,4,5]  
  7. lst.append(6)   
  8. print lst     #[1, 2, 3, 4, 5, 6]  
  9. lst.append("hello")  
  10. print lst     #[1, 2, 3, 4, 5, 6]  
  11.   
  12. #【pop】  删除一个元素,并返回此元素的值 支持索引 默认为最后一个  
  13. x = lst.pop()  
  14. print x,lst     #hello [1, 2, 3, 4, 5, 6]  #默认删除最后一个元素  
  15. x = lst.pop(0)  
  16. print x,lst     #1 [2, 3, 4, 5, 6]  删除第一个元素  
  17.   
  18. #【count】  返回一个元素出现的次数  
  19. print lst.count(2)    #1     
  20.   
  21. #【extend】  扩展列表  此方法与“+”操作的不同在于此方法改变原有列表,而“+”操作会产生一个新列表  
  22. lstextend = ["hello","world"]  
  23. lst.extend(lstextend)  
  24. print lst           #[2, 3, 4, 5, 6, 'hello', 'world']  在lst的基础上扩展了lstextend进来   
  25.   
  26. #【index】  返回某个值第一次出现的索引位置,如果未找到会抛出异常  
  27. print lst.index("hello")  #5      
  28.   
  29. #print lst.index("kitty") #ValueError: 'kitty' is not in list  出现异常  
  30.   
  31.   
  32. #【remove】 移除列表中的某个元素,如果待移除的项不存在,会抛出异常  无返回值  
  33. lst.remove("hello")  
  34. print lst     #[2, 3, 4, 5, 6, 'world']  "hello" 被移除  
  35.   
  36. #lst.remove("kitty")         #ValueError: list.remove(x): x not in list  
  37.   
  38. #【reverse】  意为反转 没错 就是将列表元素倒序排列,无返回值  
  39. print lst        #[2, 3, 4, 5, 6, 'world']  
  40. lst.reverse()   
  41. print lst        #[2, 3, 4, 5, 6, 'world']  
  42.   
  43.   
  44. #【sort】 排序  
  45. print lst    #由于上面的反转 目前排序为 ['world', 6, 5, 4, 3, 2]  
  46. lst.sort()    
  47. print lst    #排序后  [2, 3, 4, 5, 6, 'world']  
  48.   
  49. nums = [10,5,4,2,3]  
  50. print nums     #[10,5,4,2,3]  
  51. nums.sort(compare)  
  52. print nums     #[2, 3, 4, 5, 10]  

 

列表转换为迭代器。

所谓的迭代器就是具有next方法(这个方法在调用时不需要任何参数)的对象。在调用next方法时,迭代器会返回它的下一个值。如果next方法被调用,但迭代器没有值可以返回,就会引发一个StopIteration异常。迭代器相对于列表的优势在于,使用迭代器不必一次性将列表加入内存,而可以依次访问列表的数据。

依然用上面的方法查看迭代器的公共方法:

  1. lst = [1,2,3,4,5]  
  2. lstiter = iter(lst)  
  3. print [x for x in dir(numiter) if not x.startswith("__")]  
  4. >>>['next']  

没错,只有next一个方法,对于一个迭代器,可以这样操作:

  1. lst = [1,2,3,4,5]  
  2. lstiter = iter(lst)  
  3.   
  4. for i in range(len(lst)):  
  5.     print lstiter.next()  #依次打印  
  6.     1  
  7.     2  
  8.     3  
  9.     4  
  10.     5  

元组类型

元组类型和列表一样,也是一种序列,与列表不同的是,元组是不可修改的。元组的声明如下:

  1. lst = (0,1,2,2,2)  
  2. lst1=("hello",)  
  3. lst2 = ("hello")  
  4. print type(lst1)    #<type 'tuple'>  只有一个元素的情况下后面要加逗号 否则就是str类型  
  5. print type(lst2)    #<type 'str'>  

字典类型

字典类型是一种键值对的集合,类似于C#中的Dictionary<object,object>或js中的json对象。其初始化方法如下:

  1. dict1 = {}  
  2. print type(dict1)      #<type 'dict'>  声明一个空字典  
  3.   
  4. dict2 = {"name":"kitty","age":18}   #直接声明字典类型  
  5.   
  6. dict3 = dict([("name","kitty"),("age",18)])  #利用dict函数将列表转换成字典  
  7.   
  8. dict4 = dict(name='kitty',age=18)           #利用dict函数通过关键字参数转换为字典  
  9.   
  10. dict5 = {}.fromkeys(["name","age"])      #利用fromkeys函数将key值列表生成字典,对应的值为None   {'age': None, 'name': None}  

字典基本的操作方法:

  1. #【添加元素】    
  2. dict1 = {}  
  3. dict1["mykey"] = "hello world"     #直接给一个不存在的键值对赋值 即时添加新元素  
  4.   
  5. dict1[('my','key')] = "this key is a tuple"   #字典的键可以是任何一中不可变类型,例如数字、字符串、元组等  
  6.   
  7. #【键值对个数】  
  8. print len(dict1)  
  9.   
  10. #【检查是否含有键】  
  11. print "mykey" in dict1         #True  检查是否含有键为mykey的键值对  
  12. print "hello" in dict1         #False  
  13.   
  14. #【删除】  
  15. del dict1["mykey"]           #删除键为mykey的键值对  

 

继续利用上面的方法查看字典的所有公共方法:

  1. >>> [x for x in dir({}) if not x.startswith("__")]  
  2. ['clear''copy''fromkeys''get''has_key''items''iteritems''iterkeys''itervalues',  
  3.  'keys''pop''popitem''setdefault''update''values''viewitems''viewkeys''viewvalues']  
  1. dict.clear()                          删除字典中所有元素  
  2.   
  3. dict.copy()                          返回字典(浅复制)的一个副本  
  4.   
  5. dict.get(key,default=None)     对字典dict 中的键key,返回它对应的值value,如果字典中不存在此键,则返回default 的值(注意,参数default 的默认值为None)  
  6.   
  7. dict.has_key(key)                 如果键(key)在字典中存在,返回True,否则返回False. 在Python2.2版本引入in 和not in 后,此方法几乎已废弃不用了,但仍提供一个 可工作的接口。  
  8.   
  9. dict.items()                         返回一个包含字典中(键, 值)对元组的列表  
  10.   
  11. dict.keys()                          返回一个包含字典中键的列表  
  12.   
  13. dict.values()                        返回一个包含字典中所有值的列表  
  14.   
  15. dict.iter()                            方法iteritems(), iterkeys(), itervalues()与它们对应的非迭代方法一样,不同的是它们返回一个迭代器,而不是一个列表。  
  16.   
  17. dict.pop(key[, default])         和方法get()相似,如果字典中key 键存在,删除并返回dict[key],如果key 键不存在,且没有给出default 的值,引发KeyError 异常。  
  18.   
  19. dict.setdefault(key,default=None)  和方法set()相似,如果字典中不存在key 键,由dict[key]=default 为它赋值。  
  20.   
  21. dict.setdefault(key,default=None)   和方法set()相似,如果字典中不存在key 键,由dict[key]=default 为它赋值。  

布尔类型

布尔类型即True和False,和其它语言中的布尔类型基本一致。下面列出典型的布尔值

  1. print bool(0)   #False  
  2. print bool(1)   #True  
  3. print bool(-1)  #True  
  4.   
  5. print bool([])  #False  
  6. print bool(())  #False  
  7. print bool({})  #False  
  8. print bool('')  #False  
  9. print bool(None#False  

猜你喜欢

转载自blog.csdn.net/cigo_2018/article/details/80939956