一般,定义数据类型的格式都是为了设置数据的上限和下限,以便程序能够很好利用。可是,在 Python 中不须要声明变量就可让变量持有数据类型,这种功能叫做动态类型。python
Python 解释器在运行时会根据语法肯定变量的类型。例如,引号(' ')表明声明字符串值,方括号([ ])表明声明列表,大括号({ })表明声明字典,非小数表明整数(Integer)类型,带小数点表明浮点数(float)类型。编程
Python 中的全部变量、函数和模块都是对象,即万物皆对象。数组
下面是 Python 中主要的数据类型:缓存
几乎全部的编程语言都有布尔值,布尔值中有两个值,分别是 True 和 False,这些值都是常量,主要用来作赋值和比较操做。例如:网络
condition = False
if condition == True:
print("You can continue with the prpgram.")
else:
print("The program will end here.")
复制代码
输出的结果是什么取决于这条语句:数据结构
if condition:
复制代码
能够理解成:app
if condition == True:
复制代码
其实,Python 表达式也能产生布尔值的结果。socket
例如,条件表达式执行完后会产生一个布尔值,那么 Python 就会评估表达式和上下文关系建立布尔值。编程语言
因为 Python 具备许多数据结构,所以它们将使用本身的规则进行操做以在布尔值上下文你中查找结果。函数
>>> str = "Learn Python"
>>> len(str)
12
>>> len(str) == 12
True
>>> len(str) != 12
False
复制代码
某些状况下,布尔常量 True 和 False 也能够用做数字。
>>> A, B = True + 0, False + 0
>>> print(A, B)
1 0
>>> type(A), type(B)
(<class 'int'>, <class 'int'>)
复制代码
能够看到,True 能做为 1,False 能做为 0,它们在进行算术运算时能被用做数字计算。
数字是程序中运用最多的数据类型,Python 不只有整数和浮点数类型,还引入了 complex(复数) 做为一种新型的数字类型。
还须要知道几点:
j
或 J
表示复数值。例如:
num = 2
print("The number (", num, ") is of type", type(num))
num = 3.0
print("The number (", num, ") is of type", type(num))
num = 3+5j
print("The number ", num, " is of type", type(num))
print("The number ", num, " is complex number?", isinstance(3+5j, complex))
复制代码
输出结果:
The number ( 2 ) is of type <class 'int'>
The number ( 3.0 ) is of type <class 'float'>
The number (3+5j) is of type <class 'complex'>
The number (3+5j) is complex number? True
复制代码
>>> complex(1.2, 5)
(1.2+j)
复制代码
>>> import sys
>>> sys.maxsize
9223372036854775807
复制代码
>>> num = 1234567890123456789
>>> num.bit_length()
61
>>> num
1234567890123456789
>>> num = 1234567890123456789123456789012345678912345678901234567891234567890123456789
>>> num.bit_length()
250
>>> num
1234567890123456789123456789012345678912345678901234567891234567890123456789
复制代码
>>> import sys
>>> sys.float_info
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)
>>> sys.float_info.dig
15
复制代码
dig 是浮点数的最大小数位数。
用单引号 '
或双引号 "
引发来的多个字符串序列被视为字符串,任何一个字符、数字或符号均可能是字符串的一部分。
Python 支持多行字符串,在开始和结束时都使用三个引号括起来。
>>> str = 'A string wrapped in single quotes'
>>> str
'A string wrapped in single quotes'
>>> str = "A string enclosed within double quotes"
>>> str
'A string enclosed within double quotes'
>>> str = """A multiline string starts and ends with a triple quotation mark."""
>>> str
'A multiline string\nstarts and ends with\na triple quotation mark.'
复制代码
字符串类型的内存地址是不变的,意味着只会存储一次,被重复拿来使用
>>> A = 'Python3'
>>> id(A)
4460827632
>>> B = A
>>> id(B)
4460827632
复制代码
能够看到第二个字符串变量和第一个共享同一个地址。
Python 有两个流行的版本,分别是 2.7 和 3.4,Python 2 默认不支持 Unicode(ASCII),可是也能够支持。而 Python 3 字符串类型已经所有支持 Unicode(UTF-8)。
Python2 字符串类型:
>>> print(type('Python String'))
<type 'str'>
>>> print(type(u'Python Unicode String'))
<type 'unicode'>
复制代码
Python3 字符串类型:
>>> print(type('Python String'))
<class 'str'>
>>> print(type(u'Python Unicode String'))
<class 'str'>
复制代码
若是要截取字符串,可使用特殊的方括号语法提取子串实现:
>>> str = "Learn Python"
>>> first_5_chars = str[0:5]
>>> print(first_5_chars)
Learn
>>> substr_from_2_to_5 = str[1:5]
>>> print(substr_from_2_to_5)
earn
>>> substr_from_6_to_end = str[6:]
>>> print(substr_from_6_to_end)
Python
>>> last_2_chars = str[-2:]
>>> print(last_2_chars)
on
>>> first_2_chars = str[:2]
>>> print(first_2_chars)
Le
>>> two_chars_before_last = str[-3:-1]
>>> print(two_chars_before_last)
ho
复制代码
字节是不可变类型,能够用来存储字符序列(8位),范围从 0 到 255。于数组类型,可使用索引获取单个字节值,可是不能修改值。
字节和字符串的区别:
>>> empty_object = bytes(16)
>>> print(type(empty_object))
<class 'bytes'>
>>> print(empty_object)
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
复制代码
字节常常在缓冲区执行 I/O 操做,例若有一个程序正在经过网络不断接收数据,程序等待消息头和终止符出现流中后开始解析数据,过程当中一直保持着将字节追加到环缓存区中。
使用 Python 的伪代码实现这样的功能:
buf = b''
while message_not_complete(buf):
buf += read_form_socket()
复制代码
列表是相似构造一个数组,它以有序序列存储任意类型的对象。列表很是灵活,没有固定大小,索引从 0 开始。
建立一个列表的方式是经过将元素放在方括号内并用逗号分隔开来。
>>> assorted_list = [True, False, 1, 1.1, 1+2j, 'Learn', b'Python']
>>> first_element = assorted_list[0]
>>> print(first_element)
True
>>> print(assorted_list)
[True, False, 1, 1.1, (1+2j), 'Learn', b'Python']
>>> for item in assorted_list:
print(type(item))
<class 'bool'>
<class 'bool'>
<class 'int'>
<class 'float'>
<class 'complex'>
<class 'str'>
<class 'bytes'>
复制代码
>>> simpleton = ['Learn', 'Python', '2']
>>> id(simpleton)
56321160
>>> simpleton
['Learn', 'Python', '2']
>>> simpleton[2] = '3'
>>> id(simpleton)
56321160
>>> simpleton
['Learn', 'Python', '3']
复制代码
列表能够包含另外一个列表,这样的列表被称为嵌套列表。
>>> nested = [[1,1,1], [2,2,2], [3,3,3]]
>>> for items in nested:
for item in items:
print(item, end=' ')
1 1 1 2 2 2 3 3 3
复制代码
列表也支持切片操做,就像以前介绍的字符串类型那样。使用切片运算符 [ ]
能够从列表中提取一个或多个元素。
>>> languages = ['C', 'C++', 'Python', 'Java', 'Go', 'Angular']
>>> print('languages[0:3] = ', languages[0:3])
languages[0:3] = ['C', 'C++', 'Python']
>>> print('languages[2:] = ', languages[2:])
languages[2:] = ['Python', 'Java', 'Go', 'Angular']
复制代码
元组是由逗号分隔的异构(heterogeneous)集合,能够存储任何数据类型。元组和列表有类似之处,具体以下:
建立一个元组的方式是经过将元素放在封闭的圆括号内并用逗号分隔开来。
pure_tuple = ()
print (pure_tuple)
复制代码
first_tuple = (3, 5, 7, 9)
second_tuple = ('learn', 'python 3')
nested_tuple = (first_tuple, second_tuple)
print(nested_tuple)
复制代码
输出结果:
((3, 5, 7, 9), ('learn', 'python 3'))
复制代码
sample_tuple = ('Python 3',)*3
print(sample_tuple)
复制代码
输出:
('Python 3', 'Python 3', 'Python 3')
复制代码
sample_tuple = (0 ,1, 2, 3, 4)
tuple_without_first_item = sample_tuple[1:]
print(tuple_without_first_item)
tuple_reverse = sample_tuple[::-1]
print(tuple_reverse)
tuple_from_3_to_5 = sample_tuple[2:4]
print(tuple_from_3_to_5)
复制代码
输出结果:
(1, 2, 3, 4)
(4, 3, 2, 1, 0)
(2, 3)
复制代码
sample_tuple[2:4]
这里的 2 表示从元组第三个元素开始,4 表示到元组第五个元素结束并将其排除在外。
列表和元组最大的不一样是列表可变,元组不可变。Python 不容许修改建立后的元组,也就是说不能添加和删除任何元素。因此若是想更新元组中的元素就必须从新建立个新的。
元组中的元素不可修改,可是若是元素是可变对象,那么这个可变对象就是可被修改的。
例如:
>>> sample_tuple = (0 ,[1, 2, 3], 2, 3, 4)
>>> sample_tuple[1][0] = 666
>>> print(sample_tuple)
(0, [666, 2, 3], 2, 3, 4)
复制代码
由于列表是可变对象,因此可修改。
Python 支持元组的缘由:
集合支持数学运算,例如并集、交集、对称差等。集合是惟一一个不可变对象的无序集合,用大括号定义,并在元素之间用逗号隔开。
集合是从数学应用的“集合”派生而来,因此同一个元素不能出现屡次。
集合类型比列表更有优点。集合使用了哈希表的数据结构实现了检查容器内是否承载了特定元素。
可使用内置的 set() 函数建立可迭代的集合。
>>> sample_set = set("Python data types")
>>> type(sample_set)
<class 'set'>
>>> sample_set
{'e', 'y', 't', 'o', ' ', 'd', 's', 'P', 'p', 'n', 'h', 'a'}
复制代码
另外一个简单的方式是用大括号 { }
将元素括起来。
>>> another_set = {'red', 'green', 'black'}
>>> type(another_set)
<class 'set'>
>>> another_set
{'red', 'green', 'black'}
复制代码
frozen set 是传统集合的一种处理形式,数据不可变,仅支持不更改上下文使用的状况下执行方法和运算符。
>>> frozenset()
frozenset()
>>> cities = {"New York City", "Saint Petersburg", "London", "Munich", "Paris"}
>>> fset = frozenset(cities)
>>> type(fset)
<class 'frozenset'>
复制代码
使用完整的例子说明 frozen set 和正常集合的区别:
sample_set = {"red", "green"}
sample_set.add("black")
print("Standard Set")
print(sample_set)
frozen_set = frozenset(["red", "green", "black"])
print("Frozen Set")
print(frozen_set)
复制代码
输出结果:
Standard Set
{'green', 'red', 'black'}
Frozen Set
frozenset({'green', 'red', 'black'})
复制代码
字典类型是键-值对的无序集合,属于内置的映射类型,其中键映射到值。这种键值对提供了直观的数据存储方式。
字典能有效存储大量数据集,Python 对字典进行了高度优化以实现快速的数据检索。
使用大括号 { }
建立字典,其中每一个元素都是一对键和值,键和值均可以是任何数据类型。
>>> sample_dict = {'key':'value', 'jan':31, 'feb':28, 'mar':31}
>>> type(sample_dict)
<class 'dict'>
>>> sample_dict
{'mar': 31, 'key': 'value', 'jan': 31, 'feb': 28}
复制代码
字典内置访问元素方法:
>>> sample_dict = {'key':'value', 'jan':31, 'feb':28, 'mar':31}
>>> sample_dict.keys()
dict_keys(['key', 'jan', 'feb', 'mar'])
>>> sample_dict.values()
dict_values(['value', 31, 28, 31])
>>> sample_dict.items()
dict_items([('key', 'value'), ('jan', 31), ('feb', 28), ('mar', 31)])
复制代码
由于字典对象是可变的,因此能够对其进行添加、更新和删除操做。
>>> sample_dict['feb'] = 29
>>> sample_dict
{'mar': 31, 'key': 'value', 'jan': 31, 'feb': 29}
>>> sample_dict.update({'apr':30})
>>> sample_dict
{'apr': 30, 'mar': 31, 'key': 'value', 'jan': 31, 'feb': 29}
>>> del sample_dict['key']
>>> sample_dict
{'apr': 30, 'mar': 31, 'jan': 31, 'feb': 29}
复制代码
本节讲解了 Python 的已支持的数据类型,包括布尔值、数字、字符串、字节、列表、元组、集合和字典。基础比较简单,多加运用便可在实际项目中使用。