大体上把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)
>>> i=10000000000
>>> type(i)
那么为什么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(2147483648)
float类型
float类型和其它语言的float基本一致,浮点数,说白了,就是带小数点的数,精度与机器相关。例如:
>>> i = 10000.1212
>>> type(i)
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)
>>> print nums
[1, 2, 3, 4]
>>> strs = ["hello","world"]
>>> print strs
['hello', 'world']
>>> lst = [1,"hello",False,nums,strs]
>>> type(lst)
>>> 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的基础上