Python的四大基本數(shù)據(jù)類型:數(shù)值型、容器型、字符串、自定義類型。
1、 數(shù)值型
int整型對象、float浮點型、bool邏輯對象。
2、 容器型
可容納多個元素的容器對象,常用的有:list、tuple、dict、set。
# 創(chuàng)建一個list變量
lst = [1,3,5]
# 創(chuàng)建一個tuple變量
tup = (1,3,5)
# 含單個元素的元組后面必須保留一個逗號,才會被解釋為元組,否則會被認為元素本身
tup1 = (1,)
# 創(chuàng)建dict對象
dic = {'a':1, 'b':3, 'c':5}
# 創(chuàng)建一個set對象
s = {1,3,5}
案例1:去最求平均
去掉列表中的一個最小值和一個最大值后,計算剩余元素的平均值。
def score_mean(lst):
lst.sort()
lst2 = lst[1:-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乘法表
for i in range(1,10):
for j in range(1,i):
print(j, ' * ', i, '=', j*i, end=' ')
print()
案例3:樣本抽樣
from random import randint, sample
lst = [ randint(0, 50) for _ in range(100)]
print(lst[:5])
lst_sample = sample(lst, 10)
print(lst_sample)
3、 字符串
Python中沒有字符類型(char),所有的字符或者字符串都被統(tǒng)一為str對象。
str類型的常用方法:
# strip用于去除字符串前面的空格
' I love Python\n\t '.strip()
# replace用于字符串替換
'I love Python '.replace(' ', '__')
# join用于合并字符串
'_'.join(['book', 'store', 'count'])
# title用于單詞的首字母大寫
'i love china'.title()
# find用于返回匹配字符串起始位置的索引
'i love python'.find('python')
案例1:判斷str1是否由str2旋轉(zhuǎn)而來
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('bookstore', 'storebook')
print(r)
案例2: 密碼安全檢查
密碼安全要求:
- 要求密碼為 6 到 20 位
- 密碼只包含英文字母和數(shù)字
import re
pat = re.compile(r'[\da-zA-Z]{6,20}')
# 測試,查看是否整個字符串都匹配
print(pat.fullmatch('qaz12'))
print(pat.fullmatch('qaz12wsxedcrfvtgb67890942234343434'))
print(pat.fullmatch('qaz_231'))
print(pat.fullmatch('N0pass222'))
4、 自定義類型
Python 使用關(guān)鍵字 class 定制自己的類,self 表示類實例對象本身。
一個自定義類內(nèi)部包括屬性和方法,其中有些方法是自帶的。
# 定義一個Dog類
class Dog(object):
pass
# 創(chuàng)建一個Dog類型的實例
wangwang = Dog()
# 使用__dir__()查看類自帶的方法
print(wangwang.__dir__())
有些地方稱以上方法為魔法方法,它們與創(chuàng)建類時自定義個性化行為有關(guān)。比如:
-
__init__方法:能定義一個帶參數(shù)的類; -
__new__方法:自定義實例化類的行為;
-__getattribute__方法:自定義讀取屬性的行為; -
__setattr__:自定義賦值與修改屬性時的行為。
# 類的屬性
def __init__(self, name, dtype):
self.name = name
self.dtype = dtype
# 類的實例
wangwang = Dog('wangwang' , 'cute_type')
# 類的方法
def shout(self):
print('I\'m %s, type: %s' % (self.name, self.dtype))
注意:
- 自定義方法的第一個參數(shù)必須是 self,它指向?qū)嵗旧恚?Dog 類型的實例 dog;
- 引用屬性時,必須前面添加 self,比如 self.name 等。
如果想要避免屬性被修改,可以將它變?yōu)樗接凶兞浚▽傩郧凹?個_,變?yōu)樗接袑傩裕?/strong>
class Dog(object):
def __init__(self, name, dtype):
self. __name = name
self.__dtype = dtype
def shout(self):
print('I\'m %s, type: %s' % (self.name, self.dtype))
同理,方法前加 2 個 _ 后,方法變?yōu)椤八接蟹椒ā?,只能?Dog 類內(nèi)被共享使用。
def get_name(self):
return self.__name
使用Python自帶的@property類,就會優(yōu)雅地將name變?yōu)橹蛔x屬性。
class Book(object):
def __init__(self, name, sale):
self.__name = name
self.__sale = sale
@property
def name(self):
return self.__name
# 測試
a_book = Book('magic_book', 1000)
print(a_book.name)
如果要使name既可讀又可寫,就再增加一個裝飾器@name.setter
@name.setter
def name(self, new_name):
self.__name = new_name