python课程2
一 魔術方法
__getitem__ 給函數使用func[n]的方法
__contains__方法 就是函數實現in方法的魔術方法
__repr__ 通過得到一個對象的字符串表示形式的
__str__ 是調用str()實現
__add__ 實現+算術運算符
__mul__ 實現*算術運算符
二序列組成的數組
2.1 python自帶類型分類
容器序列
list tuple collections.deque
指的存放任意對象的應用
扁平序列
str bytes bytearray memoryview array.array
存放的指,還不是引用,扁平序列就是一段連續內存空間
可變序列
list bytearray array.array collections.deque memoryview
不可變序列
tuple str bytes
2.2 列表表達式
python 2 python3 區別,3有局部作用域 但是2沒有 所以列表表達式在2中有變量泄露
用列表表達式做笛卡爾積
1 colos = ["bb","as"] 2 sizes = [1,3,4] 3 4 aa = [(colo,size) for colo in colos for size in sizes] 5 print(aa)?
字符串變成asic碼的列表
tests="sfafasfzx" print([ord(test)for test in tests]) View Code?
2.3 生成器表達式
用生成器來初始化數組,元祖等其他序列類型,因為生成器遵守迭代器的協議
2.4 元組
元祖不僅僅是不可變列表,其他提供功能
1 元素的總數,元素的位置
拆包 每個類型都有拆包解包功能
fuck,fuckyou ,_ = (1,3,4,5,6,7)
fuck,fuckyou ,*otherfuck = (1,3,4,5,6,7)
str的format用法
同時指定寬度和精度的一般形式是 '[<>^]?width[,]?(.digits)?' , 其中 width 和 digits 為整數,?代表可選部分。 同樣的格式也被用在字符串的 format() 方法中。比如:
1 0.2f 保留2位小數
2 >10.1f 左邊保留10個字符長度
3 <10.1f 右邊保留10個字符長度
4 ^10.1f 居中
當跟著str后,即''.format時候,需要在前面加上: 號
當值不存在時候處理
?1 format 可以用**傳遞字典,*傳遞list進formart
2 也可以使用foramt_map傳送字典
3 當class對象 傳入時候需要用vars進行轉換
4__missing__處理當指不存在時候進行處理
class Infi:def __init__(self,name,n):self.name = nameself.n = nba = Infi('lqm',11) print(vars(ba)) s = '{name} has {n} messages' print(s.format_map(vars(ba)))print(s.format(**vars(ba))) ? 1 {'name': 'lqm', 'n': 11} 2 lqm has 11 messages 3 {'name': 'lqm', 'n': None} 4 lqm has None messages result
?
?
?
具名元祖
namedtuple 可以實現帶字段名的元祖,實際內存消耗和元祖差不多 from collections import namedtupleCity = namedtuple('city','name country pop corrd') tokyo = City('Tokyo','jp',36.33,(11,22)) print(tokyo._fields) dadi_data = ("ncr","in",21.95,223) dadi = City._make(dadi_data) print(dadi._asdict())結果 ('name', 'country', 'pop', 'corrd') OrderedDict([('name', 'ncr'), ('country', 'in'), ('pop', 21.95), ('corrd', 223)])注意方法 ._fields 獲取類的字段名
? ? ? ? ? ? ? ? ?._make 生成字段數據
? ? ? ? ? ? ? ? ._asdict() 顯示具名元祖數據
? ? ? ? ? ? ? ? ?每個字段可以存取不同的類型
?
切片
對切片賦值時候,右邊必須是可迭代的對象,就算是一個指也需要
l = list(range(10)) l[2:5] = [100] print(l)result: [0, 1, 100, 5, 6, 7, 8, 9]?
array 數組
數組只能存放int和float類型
| 'b' | signed char | int | 1 | ? |
| 'B' | unsigned char | int | 1 | ? |
| 'u' | Py_UNICODE | Unicode character | 2 | (1) |
| 'h' | signed short | int | 2 | ? |
| 'H' | unsigned short | int | 2 | ? |
| 'i' | signed int | int | 2 | ? |
| 'I' | unsigned int | int | 2 | ? |
| 'l' | signed long | int | 4 | ? |
| 'L' | unsigned long | int | 4 | ? |
| 'q' | signed long long | int | 8 | (2) |
| 'Q' | unsigned long long | int | 8 | (2) |
| 'f' | float | float | 4 | ? |
| 'd' | double | float | 8 | ? |
?
?
?
from array import array floats = array('d',[1,3,4,5])?array有更快的讀寫文件方法 frombytes tofile
數組支持深度拷貝,而list不支持
轉載于:https://www.cnblogs.com/liuqimin/p/8783803.html
總結
- 上一篇: EasyNVR无插件直播服务如何配合Ea
- 下一篇: 页面布局与编写(续2)