Python 中的数据皆是对象,比如被熟知的int
整型对象,float
双精度浮点型,bool
逻辑对象,它们都是单个元素。举两个例子:
0x
,创建一个十六进制的整数:0xa5 # 等于十进制的 165
e
创建科学计数法表示的浮点数:1.05e3 # 1050.0
可容纳多个元素的容器对象,常用的比如:list
列表对象, tuple
元组对象, dict
字典对象, set
集合对象。 Python 定义这些类型的变量,语法非常简洁。
举例如下:
[]
,创建一个list
型变量:lst = [1,3,5] # list变量
()
,创建一个tuple
型对象:tup = (1,3,5) # tuple变量
{}
另使用冒号:
,创建一个dict
对象:dic = {'a':1, 'b':3, 'c':5} # dict变量
{}
,创建一个set
对象:s = {1,3,5} # 集合变量
Python 的容器类型,list, dict, tuple, set 等能方便地实现强大的功能,下面列举几个:
1) 去最求平均
def score_mean(lst):
lst.sort()
lst2=lst[1:(len(lst)-1)]
return round((sum(lst2)/len(lst2)),1)
lst=[9.1, 9.0,8.1, 9.7, 19,8.2, 8.6,9.8]
score_mean(lst) # 9.1
2) 打印 99 乘法表
打印出如下格式的乘法表
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
一共有 10 行,第i
行的第j
列等于:j*i
,
其中,
i
取值范围:1<=i<=9
j
取值范围:1<=j<=i
根据例子分析
的语言描述,转化为如下代码:
for i in range(1,10):
...: for j in range(1,i+1):
...: print('%d*%d=%d'%(j,i,j*i),end="\t")
...: print()
3) 样本抽样
使用sample
抽样,如下例子从 100 个样本中随机抽样 10 个。
from random import randint,sample
lst = [randint(0,50) for _ in range(100)]
print(lst[:5])# [38, 19, 11, 3, 6]
lst_sample = sample(lst,10)
print(lst_sample) # [33, 40, 35, 49, 24, 15, 48, 29, 37, 24]
注意 Python 中没有像C++
表示的字符类型(char
),所有的字符或串都被统一为str
对象。如单个字符c
的类型也为str
.
str
类型会被经常使用,先列举 5 个被高频使用的方法:
strip
用于去除字符串前后的空格:In [1]: ' I love python\t\n '.strip()
Out[1]: 'I love python'
replace
用于字符串的替换:In [2]: 'i love python'.replace(' ','_')
Out[2]: 'i_love_python'
join
用于合并字符串:In [3]: '_'.join(['book', 'store','count'])
Out[3]: 'book_store_count'
title
用于单词的首字符大写:In [4]: 'i love python'.title()
Out[4]: 'I Love Python'
find
用于返回匹配字符串的起始位置索引:In [5]: 'i love python'.find('python')
Out[5]: 7
举个应用字符串的案例,判断 str1 是否由 str2 旋转而来。
字符串stringbook
旋转后得到bookstring
,写一段代码验证str1
是否为str2
旋转得到。
转化为判断:str1
是否为str2+str2
的子串
def is_rotation(s1: str, s2: str) -> bool:
if s1 is None or s2 is None:
return False
if len(s1) != len(s2):
return False
def is_substring(s1: str, s2: str) -> bool:
return s1 in s2
return is_substring(s1, s2 + s2)
测试
r = is_rotation('stringbook', 'bookstring')
print(r) # True
r = is_rotation('greatman', 'maneatgr')
print(r) # False
字符串的匹配操作除了使用str
封装的方法外,Python 的re
正则模块匹配字符串,功能更加强大且写法极为简便,广泛适用于网络爬虫和数据分析领域。
下面这个例子实现的是:密码安全检查,使用正则表达式非常容易实现。
密码安全要求:1)要求密码为 6 到 20 位; 2)密码只包含英文字母和数字
pat = re.compile(r'\w{6,20}') # 这是错误的,因为\w通配符匹配的是字母,数字和下划线,题目要求不能含有下划线
# 使用最稳的方法:\da-zA-Z满足`密码只包含英文字母和数字`
pat = re.compile(r'[\da-zA-Z]{6,20}')
选用最保险的fullmatch
方法,查看是否整个字符串都匹配:
pat.fullmatch('qaz12') # 返回 None, 长度小于6
pat.fullmatch('qaz12wsxedcrfvtgb67890942234343434') # None 长度大于22
pat.fullmatch('qaz_231') # None 含有下划线
pat.fullmatch('n0passw0Rd')
Out[4]: <re.Match object; span=(0, 10), match='n0passw0Rd'>
Python 使用关键字 class
定制自己的类,_self__
表示类实例对象本身。
一个自定义类内包括属性、方法,还有建立类是系统自带的方法。
类(对象)
class dog(object)
以上定义了一个dog对象,它继承于根类object.
类的属性
def __init__(self, name, dtype):
self.name = name
self.dtype = dtype
以上定义了 dog 对象的两个属性:name, dtype,通过init,这个系统函数是每个对象自带的。
类的方法
def shout(self):
print('I'm %s, type: %s' % (self.name, self.dtype))
注意,对象的方法参数必须要有 self,引用属性时,必须前面添加 self.name 等。
类的实例
xiaohuaDog = dog('xiaohua','quanType')
xiaohuaDog
是 dog 对象的实例.
下面的 shout() 方法,是一个 public 方法,能在外部被其他模块调用。
def shout(self):
pass
如果在 shout 前面添加2个_
后,此方法变为私有方法,只能在内部使用。
属性前加 2 个_后,属性变为私有属性。通过此机制改变属性的可读性或可写性。
def get_type(self):
return __type
通过get_type
函数,就相当于 type 修改为可读、不可写的。
再看一个例子。
自定义一个最精简的Book
类,它继承于系统的根类object
class Book(object):
pass
使用 Python 自带的装饰器@property
创建一个属性book_store_count
:
@property
def book_store_count(self):
return self._book_store_count
@book_store_count.setter
def book_store_count(self, val):
self._book_store_count = val
使用属性book_store_count
:
python_intro = Book()
python_intro.book_store_count = 100
print('store_count of python_intro is {0}'.format(
python_intro.book_store_count)) # store_count of python_intro is 100
关于创建类内属性的原理此处不展开,会在后面章节中通俗易懂的详细论述。
今天学习了 Python 的四大基本数据类型,数值型,int, float 等;容器性,list, dict, tuple, set 等;字符型,str 与正则介绍;自定义类的基本语法规则,class, 属性和方法等。
收藏
Python 中的数据皆是对象,比如被熟知的int
整型对象,float
双精度浮点型,bool
逻辑对象,它们都是单个元素。举两个例子:
0x
,创建一个十六进制的整数:0xa5 # 等于十进制的 165
e
创建科学计数法表示的浮点数:1.05e3 # 1050.0
可容纳多个元素的容器对象,常用的比如:list
列表对象, tuple
元组对象, dict
字典对象, set
集合对象。 Python 定义这些类型的变量,语法非常简洁。
举例如下:
[]
,创建一个list
型变量:lst = [1,3,5] # list变量
()
,创建一个tuple
型对象:tup = (1,3,5) # tuple变量
{}
另使用冒号:
,创建一个dict
对象:dic = {'a':1, 'b':3, 'c':5} # dict变量
{}
,创建一个set
对象:s = {1,3,5} # 集合变量
Python 的容器类型,list, dict, tuple, set 等能方便地实现强大的功能,下面列举几个:
1) 去最求平均
def score_mean(lst):
lst.sort()
lst2=lst[1:(len(lst)-1)]
return round((sum(lst2)/len(lst2)),1)
lst=[9.1, 9.0,8.1, 9.7, 19,8.2, 8.6,9.8]
score_mean(lst) # 9.1
2) 打印 99 乘法表
打印出如下格式的乘法表
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
一共有 10 行,第i
行的第j
列等于:j*i
,
其中,
i
取值范围:1<=i<=9
j
取值范围:1<=j<=i
根据例子分析
的语言描述,转化为如下代码:
for i in range(1,10):
...: for j in range(1,i+1):
...: print('%d*%d=%d'%(j,i,j*i),end="\t")
...: print()
3) 样本抽样
使用sample
抽样,如下例子从 100 个样本中随机抽样 10 个。
from random import randint,sample
lst = [randint(0,50) for _ in range(100)]
print(lst[:5])# [38, 19, 11, 3, 6]
lst_sample = sample(lst,10)
print(lst_sample) # [33, 40, 35, 49, 24, 15, 48, 29, 37, 24]
注意 Python 中没有像C++
表示的字符类型(char
),所有的字符或串都被统一为str
对象。如单个字符c
的类型也为str
.
str
类型会被经常使用,先列举 5 个被高频使用的方法:
strip
用于去除字符串前后的空格:In [1]: ' I love python\t\n '.strip()
Out[1]: 'I love python'
replace
用于字符串的替换:In [2]: 'i love python'.replace(' ','_')
Out[2]: 'i_love_python'
join
用于合并字符串:In [3]: '_'.join(['book', 'store','count'])
Out[3]: 'book_store_count'
title
用于单词的首字符大写:In [4]: 'i love python'.title()
Out[4]: 'I Love Python'
find
用于返回匹配字符串的起始位置索引:In [5]: 'i love python'.find('python')
Out[5]: 7
举个应用字符串的案例,判断 str1 是否由 str2 旋转而来。
字符串stringbook
旋转后得到bookstring
,写一段代码验证str1
是否为str2
旋转得到。
转化为判断:str1
是否为str2+str2
的子串
def is_rotation(s1: str, s2: str) -> bool:
if s1 is None or s2 is None:
return False
if len(s1) != len(s2):
return False
def is_substring(s1: str, s2: str) -> bool:
return s1 in s2
return is_substring(s1, s2 + s2)
测试
r = is_rotation('stringbook', 'bookstring')
print(r) # True
r = is_rotation('greatman', 'maneatgr')
print(r) # False
字符串的匹配操作除了使用str
封装的方法外,Python 的re
正则模块匹配字符串,功能更加强大且写法极为简便,广泛适用于网络爬虫和数据分析领域。
下面这个例子实现的是:密码安全检查,使用正则表达式非常容易实现。
密码安全要求:1)要求密码为 6 到 20 位; 2)密码只包含英文字母和数字
pat = re.compile(r'\w{6,20}') # 这是错误的,因为\w通配符匹配的是字母,数字和下划线,题目要求不能含有下划线
# 使用最稳的方法:\da-zA-Z满足`密码只包含英文字母和数字`
pat = re.compile(r'[\da-zA-Z]{6,20}')
选用最保险的fullmatch
方法,查看是否整个字符串都匹配:
pat.fullmatch('qaz12') # 返回 None, 长度小于6
pat.fullmatch('qaz12wsxedcrfvtgb67890942234343434') # None 长度大于22
pat.fullmatch('qaz_231') # None 含有下划线
pat.fullmatch('n0passw0Rd')
Out[4]: <re.Match object; span=(0, 10), match='n0passw0Rd'>
Python 使用关键字 class
定制自己的类,_self__
表示类实例对象本身。
一个自定义类内包括属性、方法,还有建立类是系统自带的方法。
类(对象)
class dog(object)
以上定义了一个dog对象,它继承于根类object.
类的属性
def __init__(self, name, dtype):
self.name = name
self.dtype = dtype
以上定义了 dog 对象的两个属性:name, dtype,通过init,这个系统函数是每个对象自带的。
类的方法
def shout(self):
print('I'm %s, type: %s' % (self.name, self.dtype))
注意,对象的方法参数必须要有 self,引用属性时,必须前面添加 self.name 等。
类的实例
xiaohuaDog = dog('xiaohua','quanType')
xiaohuaDog
是 dog 对象的实例.
下面的 shout() 方法,是一个 public 方法,能在外部被其他模块调用。
def shout(self):
pass
如果在 shout 前面添加2个_
后,此方法变为私有方法,只能在内部使用。
属性前加 2 个_后,属性变为私有属性。通过此机制改变属性的可读性或可写性。
def get_type(self):
return __type
通过get_type
函数,就相当于 type 修改为可读、不可写的。
再看一个例子。
自定义一个最精简的Book
类,它继承于系统的根类object
class Book(object):
pass
使用 Python 自带的装饰器@property
创建一个属性book_store_count
:
@property
def book_store_count(self):
return self._book_store_count
@book_store_count.setter
def book_store_count(self, val):
self._book_store_count = val
使用属性book_store_count
:
python_intro = Book()
python_intro.book_store_count = 100
print('store_count of python_intro is {0}'.format(
python_intro.book_store_count)) # store_count of python_intro is 100
关于创建类内属性的原理此处不展开,会在后面章节中通俗易懂的详细论述。
今天学习了 Python 的四大基本数据类型,数值型,int, float 等;容器性,list, dict, tuple, set 等;字符型,str 与正则介绍;自定义类的基本语法规则,class, 属性和方法等。