【Python】解析Python的标准数据类型

目录结构:

contents structure [-]

1.数值(Number)

1.1 数值类型

Python的数值类型支持整数,浮点数和复数,他们在Python中分别是int,float和complex。

整数和浮点数的表面区别就是是否有小数点,有小数点的就是浮点数,没有的就是整数。整数可以为任意长度,浮点数只能保留小数点后15位。例如:5是整数,5.0是浮点数。

复数的书写格式是x+yj,其中x是实数,y是虚数,j是表示复数的字符,例如:2+3j。

a = 5
# Type()返回变量所属的类型
# Output: <class 'int'>
print(type(a))

# isinstance() 是否是某种类型的实例
# Output: True
print(isinstance(a,int))

b = 5.0
# Output: <class 'float'>
print(type(b))

# Output: True
print(isinstance(b,float))

# Output: (8+3j)
c = 5 + 3j
print(c + 3)

# Output: True
print(isinstance(c, complex))

上面代码中,type()函数返回变量所属的类型,isinstance()函数检查变量是否属于指定类型的实例。

数值类型除了10进制,还有2进制、8进制和16进制。在Python中为了表示这些进制,只需要在数值前加上指定的前缀就可以了。

进制 前缀
二进制(Binary) '0b' or '0B'
八进制(Octal) '0o' or '0O'
十六进制(Hexadecimal) '0x' or '0X'

1.2 类型转化

我们可以把一种数值类型转化为另一种数值类型,这个过程被称为类型转化。

在数值的加、减操作中,只要有一个操作数是浮点数,那么其中的整数就会隐式地转化为浮点数(自动地)。
例如:

>>> 1 + 2.0
3.0

在Python中还可以使用int(),float(),complex()方法显式地进行强制类型转化。

>>> int(12.1)
12
>>> int(-12.1)
-12
>>> int(--12.1)
12
>>> float(12)
12.0
>>> float('12.1')
12.1
>>> float('-12.1')
-12.1
>>> complex(2)
(2+0j)
>>> complex(2.1)
(2.1+0j)
>>> complex('2+3j')
(2+3j)

1.3 Python中的Decimal数据类型

Python中的内置类型float并不能精确的存储所有的小数。这并不只是Python语言中存在的问题,关于更多读者可以查阅IEEE 754标准。

>>> 1.1 + 2.2
3.3000000000000003

从上面的运算可以看出,我们只需要得到3.3就可以了,然而却得到了3.3000000000000003,为了解决这个问题,我们可以使用Python的Decimal类。

# 引入Decimal
from  decimal import Decimal

# val的值是Decimal('3.3')
val = Decimal('1.1')+Decimal('2.2')

# Output:<class 'decimal.Decimal'>
print(type(val))

# Output:3.3
print(val)

在使用Decimal类之前,应该先引入decimal模块。

1.4 Python中的分数

Python还提供了Fractions类,该类可以提供分数操作。在使用Fractions之前,应该先引入fractions模块。

# 引入Fraction
from fractions import Fraction

# Output:1/2
print(Fraction(0.5))

# Output:1/3
print(Fraction(1,3))

# Output: 2/3
print(Fraction(1,3) + Fraction(1,3))

# Output: 6/5
print(1 / Fraction(5,6))

当我们给Fraction传入浮点数时,可能会得到一些没有用处的结果,这主要是由于浮点数的不精确存储造成的。为了解决该问题,Fraction类允许我们传入一个字符串,并且Fraction会把字符串解析成Decimal类型。

from fractions import Fraction

# 浮点数不精确存储造成的问题
# Output:2476979795053773/2251799813685248
print(Fraction(1.1))

# 传入字符串,Fraction会把字符串解析成Decimal类型,解决了浮点数不精确存储的问题
# Output:11/10
print(Fraction('1.1'))

1.5 Python中的算术方法

Python提供了math和random模块,提供了多种的算术运算。

math模块中的部分方法:

import math

# 圆周率
# Output: 3.141592653589793
print(math.pi)

# 余弦
# Output: -1.0
print(math.cos(math.pi))

# 指数
# Output: 22026.465794806718
print(math.exp(10))

# 对数
# Output: 3.0
print(math.log10(1000))

# 反正弦
# Output: 1.1752011936438014
print(math.sinh(1))

# 阶乘
# Output: 720
print(math.factorial(6))

random模块中的部分方法:

import random

# 随机获取[16,20)中的一个整数
# Output: 16
print(random.randrange(10,20))

x = ['a', 'b', 'c', 'd', 'e']

# 随机获取一个元素
# Get random choice
print(random.choice(x))

# 随机组织x中的元素顺序
# Shuffle x
random.shuffle(x)

# Print the shuffled x
print(x)

# [0,1)的随机值
# Print random element
print(random.random())

2.字符串(String)

字符串的创建

Python中的字符串可以由双引号、单引号或三重引号创建,三重引号既可以包含单行文本,也可以包含多行文本。
例如:

# 单引号可以表示字符串
my_string = 'Hello'
print(my_string)

# 双引号可以表示字符串
my_string = "Hello"
print(my_string)

# 三重引号可以包含多行文本
my_string = '''Hello,
           welcome'''
print(my_string)

my_string = """Hello, welcome to
           the world of Python"""
print(my_string)

输出结果为:

Hello
Hello
Hello,
           welcome
Hello, welcome to
           the world of Python


字符串的访问

在python中可以通过下标的方式来访问字符串。开始的下标是0,结束的下标是字符串的长度减一。当访问下标越界时,会抛出IndexError错误。

Python中的字符串还支持负的下标,-1代表最后一个元素,-2代表倒数第二个元素,....。还可以通过冒号访问字符串中的一组字符。

str = 'programiz'
print('str = ', str)

#第一个字符
print('str[0] = ', str[0])

#最后一个字符
print('str[-1] = ', str[-1])

#从下标为1到下标为5(不包括)的字符,[1,5)
print('str[1:5] = ', str[1:5])

#从下标为5到下标为-2(不包括)的字符串,[5,-2)
print('str[5:-2] = ', str[5:-2])

输出结果为:

str =  programiz
str[0] =  p
str[-1] =  z
str[1:5] =  rogr
str[5:-2] =  am


字符串的修改

由于字符串是不可更改的,所以任何试图修改字符串中的值都会引发错误。我们只能重新分配一个不同的字符串和之前的字符串具有相同的名称,以达到修改的效果。

>>> my_string = 'programiz'
>>> my_string[5] = 'a'
...
TypeError: 'str' object does not support item assignment
>>> my_string = 'Python'
>>> my_string
'Python'

我们不可删除和修改字符串中的字符,但是我们可以删除整个字符串(使用 del 关键字)

>>> del my_string[1]
...
TypeError: 'str' object doesn't support item deletion
>>> del my_string
>>> my_string
...
NameError: name 'my_string' is not defined

字符串的迭代

使用for loop语句,我们可以循环迭代字符串。

count = 0
for letter in 'Hello World':
    if(letter == 'l'):
        count += 1
print(count,'letters found')

字符串的成员字符测试

我们可以测试一个字符串是否包含在另一个字符串中,使用关键字 in

>>> 'a' in 'program'
True
>>> 'at' not in 'battle'
False

字符串转换为枚举对象

enumerate函数返回一个枚举对象,它包含了键值对。

str = 'cold'

# enumerate()
list_enumerate = list(enumerate(str))
print('list(enumerate(str) = ', list_enumerate)

输出结果为:

list(enumerate(str) =  [(0, 'c'), (1, 'o'), (2, 'l'), (3, 'd')]

字符串的长度

len函数返回字符串的长度

str = 'cold'

# Output:len(str) = 4
print('len(str) = ', len(str))

转义字符

转义字符 描述
\\ 反斜杠
\' 单括号
\" 双括号
\a 响铃符
\b 退格符
\n 换行符
\r 回车符
\t 水平制表符
\v 垂直制表符
\xHH 十六进制


转义字符的忽略

行字符串可以忽略字符串中的转义字符,行字符串的书写只需要在字符串的最前面加上r或R就可以了。

>>> print("This is \x61 \ngood example")
This is a
good example
>>> print(r"This is \x61 \ngood example")
This is \x61 \ngood example


格式字符串

format()在格式字符串中使用地非常广泛,格式字符串包含大括号{}作为占位符或替换字段,这些字段将被替换。

# default(implicit) order
default_order = "{}, {} and {}".format('John','Bill','Sean')
print('\n--- Default Order ---')
print(default_order)

# order using positional argument
positional_order = "{1}, {0} and {2}".format('John','Bill','Sean')
print('\n--- Positional Order ---')
print(positional_order)

# order using keyword argument
keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean')
print('\n--- Keyword Order ---')
print(keyword_order)

结果为:

--- Default Order ---
John, Bill and Sean

--- Positional Order ---
Bill, John and Sean

--- Keyword Order ---
Sean, Bill and John

3.列表(List)

3.1 List元素的创建

在Python程序中,列表由方括号创建,列表元素由逗号隔开。

# 空列表
my_list = []

# 整数列表
my_list = [1, 2, 3]

# 混合数据类型列表
my_list = [1, "Hello", 3.4]

# 将其他的列表作为改列表的子元素
my_list = ["mouse", [8, 4, 6], ['a']]


除了这种传统的创建方式,还可以有更优雅的创建方式(列表解析),例如:

pow2 = [2 ** x for x in range(10)]

# Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
print(pow2)


列表中可以包含多个for或if语句,if语句可以起到过滤子项的作用,下面是一些案例:

>>> pow2 = [2 ** x for x in range(10) if x > 5]
>>> pow2
[64, 128, 256, 512]
>>> odd = [x for x in range(20) if x % 2 == 1]
>>> odd
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x+y for x in ['Python ','C '] for y in ['Language','Programming']]
['Python Language', 'Python Programming', 'C Language', 'C Programming']

3.2 List元素的遍历、增加、删除和修改

列表的访问

my_list = ['p','r','o','b','e']
# Output: p
print(my_list[0])

# Output: pr
print(my_list[0:2])

# Output: e
print(my_list[-1])

# Output: prob
print(my_list[0,-1])


列表成员测试

可以使用关键字key,测试某一项是否在(或不在)列表中

my_list = ['p','r','o','b','l','e','m']

# Output: True
print('p' in my_list)

# Output: False
print('a' in my_list)

# Output: True
print('c' not in my_list)


列表的遍历

可以使用for loop方法遍历列表中的元素

for fruit in ['apple','banana','mango']:
    print("I like",fruit)


列表的增加、修改、删除

列表是可更改的,意味着它的元素可以更改和删除,这一点和Tuple与String不一样。

使用=符,修改列表中元素的值

# values
odd = [2, 4, 6, 8]

# 改变第一个元素的值
odd[0] = 1            

# Output: [1, 4, 6, 8]
print(odd)

# 改变第二个到第四个元素的值
odd[1:4] = [3, 5, 7]  

# Output: [1, 3, 5, 7]
print(odd)     


使用+操作符,连接两个列表。
使用*操作符,重复列表给定的次数。
使用:(切片操作符),插入一组元素到指定的位置。
使用append()方法,添加某一项到列表中。
使用extend()方法,添加几项到列表中。
使用insert()方法,插入元素到指定的位置。

odd = [1, 3, 5]
#apppend()方法
odd.append(7)

# Output: [1, 3, 5, 7]
print(odd)

#extend()方法
odd.extend([9, 11, 13])
# Output: [1, 3, 5, 7, 9, 11, 13]
print(odd)

odd = [1, 3, 5]
# +操作符
# Output: [1, 3, 5, 9, 7, 5]
print(odd + [9, 7, 5])

# *操作符
#Output: ["re", "re", "re"]
print(["re"] * 3)

odd = [1, 9]
# insert()方法
odd.insert(1,3)

# Output: [1, 3, 9]
print(odd)

# : 操作符
odd = [1,3, 9]

odd[2:2] = [5, 7]

# Output: [1, 3, 5, 7, 9]
print(odd)


可以使用del关键字修改List中一个或一组元素的值。

my_list = ['p', 'r', 'b', 'l', 'e', 'm']

# Output: ['p', 'r', 'b', 'l', 'e', 'm']     
print(my_list)

# delete multiple items
del my_list[1:5]  

# Output: ['p', 'm']
print(my_list)

# delete entire list
del my_list       

# Error: List not defined
print(my_list)


使用remove()方法可以移除给定的值,pop()移除给定下标的项。pop()若不提供下标值,则会移除并且返回最后一项,借助这个方法可以像操作栈一样操作List(先进后出)。

my_list = ['r', 'o', 'b', 'l', 'e', 'm']

# Output: ['r', 'o', 'b', 'l', 'e', 'm']
print(my_list)

# Output: 'o'
print(my_list.pop(1))

# Output: ['r', 'b', 'l', 'e', 'm']
print(my_list)

# Output: 'm'
print(my_list.pop())

# Output: ['r', 'b', 'l', 'e']
print(my_list)

4.集合(Set)

Set是一个未排序的数据项集合,每一个元素都必须是唯一的和不可更改的。注意,Set集合本身是可更改的,我们可以从中添加和删除元素。

4.1 Set元素的创建

Set集合由花括号{}创建,集合中的元素使用逗号分隔开。Set集合中可以包含任何数量的数据项,它们可以是任何的数据类型(整数、浮点数、元组等等),但是Set集合中的元素都必须是不可更改的,比如:List或Dictionary都是可更改的数据类型,应此不能作为Set的数据项。

# 整数集合
my_set = {1, 2, 3}
print(my_set)

# 混合类型数据集合
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)


由于Set集合中不能包含可更改的数据项(比如List和Dictionary),若需要添加可更改的数据类型项,可使用set()构造方法,set()构造方法可将一个可迭代对象转化为Set集合。
例如:

# Set集合中不存在重复值
# Output: {1, 2, 3, 4}
my_set = {1,2,3,4,3,2}
print(my_set)

# set集合中不能有可更改的数据项
# 这里的 [3, 4] 是一个可更改的List数据对象
# TypeError: unhashable type: 'list'
#my_set = {1, 2, [3, 4]}

# 使用set构造函数,从List中构造set对象
# Output: {1, 2, 3}
my_set = set([1,2,3,2])
print(my_set)

4.2 Set元素的遍历、增加、删除和修改

Set元素的遍历

使用for loop语句可以遍历集合

>>> for letter in set("apple"):
...     print(letter)
...    
a
p
e
l

Set元素的增加、修改

Set中的数据项是不可修改的,但是Set集合是可修改的。
添加单个元素可以使用add方法,添加多个元素可以使用update方法

# 初始化Set集合
my_set = {1,3}
print(my_set)

# set 集合不支持下标
# TypeError: 'set' object does not support indexing
# my_set[0]

# 使用add方法,添加元素
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)

# 使用update方法,添加多个元素(并且会去重)
# Output: {1, 2, 3, 4}
my_set.update([2,3,4])
print(my_set)

# 使用update方法,添加set和List
# Output: {1, 2, 3, 4, 5, 6, 8}
my_set.update([4,5], {1,6,8})
print(my_set)

Set元素的删除

移除Set中元素的值可以使用remove()或discard()方法,这两个方法都可以移除数据项,它们唯一的区别是:当被移除的数据项不存在时,discard()方法什么也不会做;而remove()方法会抛出异常。

# 初始化my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)

# discard一个元素
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)

# remove一个元素
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)

# discard一个不存在的元素
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)

# remove一个不存在的元素,抛出异常
# Output: KeyError: 2
#my_set.remove(2)


同样我们也可以使用pop()方法,弹出指定的元素。clear()清除整个set集合。

4.3 Set的交集、并集、差集操作

Set并集操作


集合A与集合B的并集是两个集合的所有元素,并集使用|符号,也可以使用union()方法。

# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use | operator
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(A | B)


Set交集操作


集合A和集合B的交集是两个集合的重叠部分,交集使用&符号,也可以使用intersection()方法。

# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use & operator
# Output: {4, 5}
print(A & B)


Set差集操作


集合A与集合B的差(A-B)由所有属于A且不属于B的元素组成的集合,差集使用-符号,也可以使用difference()方法。

# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use - operator on A
# Output: {1, 2, 3}
print(A - B)


Set对称差集合


集合A与集合B的对称差集为集合A与集合B中所有不属于A∩B的元素的集合,对称差集使用^符号,也可以使用symmetric_difference()方法

A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use ^ operator
# Output: {1, 2, 3, 6, 7, 8}
print(A ^ B)

5.元组(Tuple)

Tuple和List非常相似,但Tuple一旦创建后就不能再更改,而List可以更改。

5.1 Tuple元素的创建

元组由一对括号()创建(括号可写可不写),元组中的元素由逗号分隔开。

# 空元组
# Output: ()
my_tuple = ()
print(my_tuple)

# 含有三个整数元素的元组
# Output: (1, 2, 3)
my_tuple = (1, 2, 3)
print(my_tuple)

# 混合数据类型的元组
# Output: (1, "Hello", 3.4)
my_tuple = (1, "Hello", 3.4)
print(my_tuple)

# 元组中嵌套内部元组和List
# Output: ("mouse", [8, 4, 6], (1, 2, 3))
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)

# 创建元组不使用括号,称为:元组包装
# Output: 3, 4.6, "dog"
my_tuple = 3, 4.6, "dog"
print(my_tuple)

# 元组解包
# Output:
# 3
# 4.6
# dog
a, b, c = my_tuple
print(a)
print(b)
print(c)

创建单个元素的元组,需要在元素后额外加上逗号,例如:

# 只有括号,my_tuple是字符串类型
# Output: <class 'str'>
my_tuple = ("hello")
print(type(my_tuple))

# 在元素后加上逗号,my_tuple是元组类型
# Output: <class 'tuple'>
my_tuple = ("hello",)  
print(type(my_tuple))

# 括号可写可不写
# Output: <class 'tuple'>
my_tuple = "hello",
print(type(my_tuple))

5.2 Tuple元素的访问、遍历

下标访问:

my_tuple = ('p','e','r','m','i','t')

# Output: 'p'
print(my_tuple[0])

# Output: 't'
print(my_tuple[5])

# tuple嵌套
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

# nested index
# Output: 's'
print(n_tuple[0][3])

# nested index
# Output: 4
print(n_tuple[1][1])


负值下标:

my_tuple = ('p','e','r','m','i','t')

# Output: 't'
print(my_tuple[-1])

# Output: 'p'
print(my_tuple[-6])


访问元组中的一组子元素:

my_tuple = ('p','r','o','g','r','a','m','i','z')

# 从第2个到第4个元素
# Output: ('r', 'o', 'g')
print(my_tuple[1:4])

# 从开始到倒数第8个元素
# Output: ('p', 'r')
print(my_tuple[:-7])

# 从第8个元素到结束的元素
# Output: ('i', 'z')
print(my_tuple[7:])

# 从开始到结束的所有元素
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple[:])

6.字典(Dictionary)

Dictionary是一个未排序的数据项集合,其它的复合数据结构都只含有值作为它的元素,而dictionary既含有键,也含有值。

6.1 Dictionary的创建

Dictionary的创建由花括号符号{}完成,其中的元素由逗号隔开,键和值由冒号隔开。

Dictionary中的key必需是不可更改的数据类型(string,number,tuple或其他的不可更改的数据类型)

# 空的Dictionary
my_dict = {}

# 使用integer作为Dictionary的key
my_dict = {1: 'apple', 2: 'ball'}

# 使用混合数据类型作为Dictionary的key
my_dict = {'name': 'John', 1: [2, 4, 3]}

# 使用 dict() 构造函数创建Dictionary对象
my_dict = dict({1:'apple', 2:'ball'})

# 从一个包含Tuple的List集合中创建Dictionary
my_dict = dict([(1,'apple'), (2,'ball')])

6.2 Dictionary的遍历、增加、删除、修改

Dictionary的遍历

squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
    print(i,":",squares[i])


Dictionary的增加、修改

Dictionary是可修改的,所以我们可以添加一个新的数据项或改变数据项中原有的值。如果key已经存在了,那么value将会被更新;如果key不存在,那么一个新的键值对将会被添加到Dictionary中。

my_dict = {'name':'Jack', 'age': 26}

# 更新值
my_dict['age'] = 27

#Output: {'age': 27, 'name': 'Jack'}
print(my_dict)

# 添加值
my_dict['address'] = 'Downtown'  

# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
print(my_dict)


Dictionary元素的删除和移动

我们可以使用pop()方法从Dictionary中弹出指定的键值对,它会返回键值对中的值。

popitem()方法可以被用来移除和返回任意数据项(key,value)。

clear()方法可以清除Dictionary中的所有数据。

del关键字移除某个数据项或是整个Dictionary集合。

# 创建一个dictionary
squares = {1:1, 2:4, 3:9, 4:16, 5:25}  

# 移除指定的键值对,返回值
# Output: 16
print(squares.pop(4))  

# Output: {1: 1, 2: 4, 3: 9, 5: 25}
print(squares)

# 移除一个键值对
# Output: (1, 1)
print(squares.popitem())

# Output: {2: 4, 3: 9, 5: 25}
print(squares)

# 删除一个键值对
del squares[5]  

# Output: {2: 4, 3: 9}
print(squares)

# 移除所有的数据项
squares.clear()

# Output: {}
print(squares)

# 删除整个dictionary数据
del squares

# Throws Error
# print(squares)

猜你喜欢

转载自www.cnblogs.com/HDK2016/p/10793131.html
今日推荐