python数据皆是对象,例如熟知的int整型对象,float双精度浮点型对象,bool逻辑对象,都是单个元素。
- 前缀加0x,创建一个十六进制的整数:0xa5 # 等于十进制的165
- 使用e创建科学计数法表示的浮点数:1.05e3 # 1050.0
python数据类型
容器型
可容纳多个元素的容器对象,常用的比如: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 等能方便地实现强大的功能,给出如下代码:
- 去最求平均值
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
- 打印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
其中, 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()
- 样本抽样
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]
利用sample抽样,从100个样本抽取随机10个。
字符串
注意:Python 中没有像C++表示的字符类型(char),所有的字符或串都被统一为str对象。如单个字符c的类型也为str。
- 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 + str2的字串?
给出示例,判定str1是否由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正则模块匹配字符串,功能更加强大且写法极为简便,广泛适用于网络爬虫和数据分析领域。
密码安全检查
要求:密码为 6 到 20 位;密码只包含英文字母和数字。
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 表示类实例对象本身。 一个自定义类内包括属性、方法,还有建立类是系统自带的方法。
- 类(对象),定义一个dog对象,继承object:
class dog(object)
- 类的方法:
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