函數(shù)
函數(shù)的定義
封閉一個(gè)功能
- 節(jié)省代碼,減少重復(fù)率
- 提高代碼可讀性
函數(shù)的結(jié)構(gòu)
def func():
pass
函數(shù)的返回值retrun
1,結(jié)束函數(shù)
2,給函數(shù)的調(diào)用者(執(zhí)行者)返回值
只有return -->None
return 單個(gè)值:返回單個(gè)值,不改變數(shù)據(jù)類(lèi)型
return 多個(gè)值:以元組的形式返回
沒(méi)有return:默認(rèn)返回None
函數(shù)的參數(shù)
形參
位置參數(shù):按順序一一對(duì)應(yīng)
默認(rèn)參數(shù):傳值即覆蓋
動(dòng)態(tài)參數(shù):*args, **kwargs萬(wàn)能參數(shù)
當(dāng)函數(shù)定義的時(shí)候(*,**的作用):
*, **代表聚合,*將實(shí)參對(duì)應(yīng)的所有位置參數(shù)聚合到一個(gè)元組,賦值給
args,**將實(shí)參對(duì)應(yīng)的所有的關(guān)鍵字參數(shù)聚合到一個(gè)字典中,賦值給kwargs
當(dāng)函數(shù)調(diào)用的時(shí)候(*,**的作用):
*,**代表打散。*是將所有的iterable元素打散成實(shí)參的位置參數(shù)。
**是將字典的所有鍵值對(duì)打散成關(guān)鍵字參數(shù)。
形參的順序:位置參數(shù),*args, 默認(rèn)參數(shù), **kwargs
實(shí)參
位置參數(shù):按順序一一對(duì)應(yīng)
關(guān)鍵字參數(shù):name='python'一一對(duì)應(yīng)
混合參數(shù):關(guān)鍵字參數(shù)一定要放在位置參數(shù)后面
內(nèi)存,空間
全局作用域
全局名稱(chēng)空間存儲(chǔ)當(dāng)前py文件:變量與值的對(duì)應(yīng)關(guān)系
內(nèi)置名稱(chēng)空間builtins,模塊
局部作用域
局部名稱(chēng)空間
當(dāng)函數(shù)執(zhí)行時(shí),內(nèi)存臨時(shí)開(kāi)辟一個(gè)空間存儲(chǔ)函數(shù)內(nèi)部變量與值的關(guān)系,隨著函數(shù)的結(jié)束而消失。
加載順序:
內(nèi)置名稱(chēng)空間-->程序運(yùn)行時(shí) 全局名稱(chēng)空間-->函數(shù)調(diào)用時(shí) 局部名稱(chēng)空間
取值順序:就近原則LEGB
L-Local(function);函數(shù)內(nèi)的名字空間
E-Enclosing function locals;外部嵌套函數(shù)的名字空間(例如closure)
G-Global(module);函數(shù)定義所在模塊(文件)的名字空間
B-Builtin(Python);Python內(nèi)置模塊的名字空間
global nonlocal
global
1,在函數(shù)內(nèi)部,對(duì)全局作用域的變量進(jìn)行修改
2,在函數(shù)內(nèi)部,聲明一個(gè)全局變量
nonlocal 下級(jí)函數(shù)對(duì)上級(jí)函數(shù)非全局變量進(jìn)行修改
函數(shù)名的應(yīng)用
1,函數(shù)名即函數(shù)地址
2,函數(shù)名可以作為變量
3,函數(shù)名可以作為函數(shù)的參數(shù)
4,函數(shù)名可以作為函數(shù)的返回值
5,函數(shù)名可以作為容器類(lèi)類(lèi)型的元素
閉包
內(nèi)層函數(shù)對(duì)外層函數(shù)非全局變量的引用,并將內(nèi)層函數(shù)函數(shù)名返回
機(jī)制:python解釋器遇到閉包,那么這個(gè)空間不會(huì)隨著函數(shù)的結(jié)束而釋放
閉包的應(yīng)用場(chǎng)景
裝飾器
爬蟲(chóng)
迭代器
1,可迭代對(duì)象:內(nèi)部含有__iter__方法
2,迭代器:內(nèi)部含有__iter__方法和__next__
3,可迭代對(duì)象-->迭代器iter(可迭代對(duì)象)
4,迭代器取值__next__()、next()或for循環(huán)
close()
生成器
通過(guò)python代碼寫(xiě)的迭代器,本質(zhì)就是迭代器
生成器的形成方式:
1,生成器函數(shù)人(含有yield)
send與next區(qū)別
以后加
2,生成器推導(dǎo)式
循環(huán)模式(變量(加工后的變量)for i in iterable)
篩選模式 (變量(加工后的變量)for i in iterable if 條件)
內(nèi)置函數(shù)
查看python的內(nèi)置函數(shù)
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
面向?qū)ο笙嚓P(guān)(9)
定義特殊方法的裝飾器(3)
classmethod
stacticmethod
property
property是一個(gè)裝飾器函數(shù)
所有的裝飾器函數(shù)都怎么用? 在函數(shù)、方法、類(lèi)的上面一行直接@裝飾器的名字
裝飾器的分類(lèi):
裝飾函數(shù)
裝飾方法 : property
裝飾類(lèi)
class Student:
def __init__(self,name,age):
self.__name = name
self.age = age
@property # 將一個(gè)方法偽裝成一個(gè)屬性
def name(self):
return self.__name
zhuge = Student('諸葛',20)
print(zhuge.name)
from math import pi
class Circle:
def __init__(self,r):
self.r = r
@property
def area(self):
return self.r ** 2 * pi
@property
def perimeter(self):
return 2 * self.r * pi
c1 = Circle(10)
print(c1.area)
print(c1.perimeter)
c1.r = 5
print(c1.area)
print(c1.perimeter)
判斷對(duì)象/類(lèi)與類(lèi)間的關(guān)系(2)
isinstance
issubclass
所有類(lèi)的基類(lèi) object
繼承相關(guān) super
封裝相關(guān) vars
數(shù)據(jù)類(lèi)型相關(guān) type
作用域相關(guān) ★★★★★
locals() 函數(shù)會(huì)以字典的類(lèi)型返回當(dāng)前位置的全部局部變量。若在最外面,與globals()相同。
globals() 函數(shù)以字典的類(lèi)型返回全部全局變量。
a = 1
b = 2
def f1():
c = 1
print('inner locals>>>>', locals())
f1()
print('globals>>>>', globals())
print('outer locals>>>>', locals())
print(globals() == locals()) ## 若在最外面,與globals()相同。結(jié)果為T(mén)rue
'''
inner locals>>>> {'c': 1}
globals>>>> {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000262523AC1D0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:\\oldboy_project\\test3.py', '__cached__': None, 'a': 1, 'b': 2, 'f1': <function f1 at 0x00000262522A2E18>}
outer
locals >>>> {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000262523AC1D0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:\\oldboy_project\\test3.py', '__cached__': None, 'a': 1, 'b': 2, 'f1': <function f1 at 0x00000262522A2E18>}
True
'''
其他相關(guān)
字符串類(lèi)型代碼的執(zhí)行 eval,exec,complie,不建議使用★★★☆☆
- eval執(zhí)行的代碼字符串有返回值,會(huì)接收。
- exec不接收返回值。
- compile() 函數(shù)將一個(gè)字符串編譯為字節(jié)代碼
## print(eval('x')) ## not defined
x = 1
print(eval('x + 3')) ## 4
print(exec('x + 3')) ## None
輸入輸出相關(guān) input,print ★★★★★
input:函數(shù)接受一個(gè)標(biāo)準(zhǔn)輸入數(shù)據(jù),返回為 string 類(lèi)型。參數(shù)默認(rèn)為None,若給了字符串,會(huì)出現(xiàn)提示內(nèi)容。
print:打印輸出。
print(*args, sep=' ', end='\n', file=sys.stdout, flush=False)
sep 是args每個(gè)參數(shù)顯示的間隔。
end 是最后以什么結(jié)束。
file 接收文件句柄,可以賦值給一個(gè)文本文件。
flush 立即把內(nèi)容輸出到流文件,不作緩存
with open('print.txt', mode='w', encoding='utf-8') as f:
print('hello world!I am learning python.', file=f)
## 命令行中沒(méi)有顯示結(jié)果,而新建了一個(gè)“print.txt"文件,里面有所寫(xiě)的內(nèi)容。
print(1, 2, 3, sep='|') ## 1|2|3
內(nèi)存相關(guān) hash id ★★★☆☆
- hash:獲取一個(gè)對(duì)象(可哈希對(duì)象:int,str,Bool,tuple)的哈希值。
hash一般會(huì)得到一個(gè)長(zhǎng)度為18的數(shù)字,
若是數(shù)值長(zhǎng)度超過(guò)18會(huì)得到一個(gè)長(zhǎng)度18的數(shù)字。
長(zhǎng)度小于18會(huì)是它原來(lái)的數(shù)值。
>>> a = 100
>>> b = '100'
>>> c = True
>>> tu = (1, 2)
>>> hash(a) #數(shù)字還是它所顯示的值。
100
>>> hash(b)
5677959494014640638
>>> hash(c)
1
>>> hash(tu)
3713081631934410656
- id: 獲取該對(duì)象的內(nèi)存地址。
文件操作相關(guān)
open() ★★★★★
函數(shù)用于打開(kāi)一個(gè)文件,創(chuàng)建一個(gè) file 對(duì)象,相關(guān)的方法才可以調(diào)用它進(jìn)行讀寫(xiě)。
模塊相關(guān)import ★★★☆☆
import:函數(shù)用于動(dòng)態(tài)加載類(lèi)和函數(shù) 。
幫助 help:函數(shù)用于查看函數(shù)或模塊用途的詳細(xì)說(shuō)明。 ★★☆☆☆
name = 'alex'
print(help(str))
調(diào)用相關(guān) callable ★★★☆☆
函數(shù)用于檢查一個(gè)對(duì)象是否是可調(diào)用的。如果返回True,object仍然可能調(diào)用失敗;但如果返回False,調(diào)用對(duì)象ojbect絕對(duì)不會(huì)成功。
>>> def f1():
... print('a')
...
>>> callable(f1)
True
>>> name = 'python'
>>> callable(name)
False
查看內(nèi)置屬性 dir ★★★☆☆
函數(shù)不帶參數(shù)時(shí),返回當(dāng)前范圍內(nèi)的變量、方法和定義的類(lèi)型列表;帶參數(shù)時(shí),返回參數(shù)的屬性、方法列表。
如果參數(shù)包含方法dir(),該方法將被調(diào)用。如果參數(shù)不包含dir(),該方法將最大限度地收集參數(shù)信息。
>>> s = 'abc'
>>> dir(s)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
迭代生成器相關(guān)
range:函數(shù)可創(chuàng)建一個(gè)整數(shù)對(duì)象,一般用在 for 循環(huán)中。
python2x: range(3) ---> [0,1,2] 列表
xrange(3) ---> 一個(gè)生成器
python3x: range(3) ---> range(0,3) 可迭代對(duì)象
next:內(nèi)部實(shí)際使用了next方法,返回迭代器的下一個(gè)項(xiàng)目。
## 首先獲得Iterator對(duì)象:
it = iter([1, 2, 3, 4, 5])
## 循環(huán):
while True:
try:
## 獲得下一個(gè)值:
x = next(it)
print(x)
except StopIteration:
## 遇到StopIteration就退出循環(huán)
break
iter:函數(shù)用來(lái)生成迭代器(即一個(gè)可迭代對(duì)象,生成迭代器)。
from collections import Iterable
from collections import Iterator
l = [1,2,3]
print(isinstance(l,Iterable)) ## True
print(isinstance(l,Iterator)) ## False
l1 = iter(l)
print(isinstance(l1,Iterable)) ## True
print(isinstance(l1,Iterator)) ## True
基礎(chǔ)數(shù)據(jù)類(lèi)型相關(guān)
數(shù)字相關(guān)
數(shù)據(jù)類(lèi)型(4)
bool :用于將給定參數(shù)轉(zhuǎn)換為布爾類(lèi)型,如果沒(méi)有參數(shù),返回 False。
>>> bool()
False
>>> bool(0)==bool('')==bool([])==bool(tuple())==bool(set())==bool({})
True
int:函數(shù)用于將一個(gè)字符串或數(shù)字轉(zhuǎn)換為整型。
>>> int('10', base=2) #二進(jìn)制轉(zhuǎn)十進(jìn)制
2
>>> int('10', base=8) #八進(jìn)制轉(zhuǎn)十進(jìn)制
8
>>> int('1e', base=16) #十六進(jìn)制轉(zhuǎn)十進(jìn)制
30
>>> int(3.8) ## 浮點(diǎn)數(shù)強(qiáng)制轉(zhuǎn)整形
3
>>> int() ## 默認(rèn)為0
0
float:函數(shù)用于將整數(shù)和字符串轉(zhuǎn)換成浮點(diǎn)數(shù)。
>>> float()
0.0
>>> float('+1.23')
1.23
>>> float(' -12345\n')
-12345.0
>>> float('1e-003')
0.001
>>> float('+1E6')
1000000.0
>>> float('-Infinity')
-inf
complex:
函數(shù)用于創(chuàng)建一個(gè)值為 real + imag * j 的復(fù)數(shù)或者轉(zhuǎn)化一個(gè)字符串或數(shù)為復(fù)數(shù)。如果第一個(gè)參數(shù)為字符串,則不需要指定第二個(gè)參數(shù)。
進(jìn)制轉(zhuǎn)換(3)
bin:將十進(jìn)制轉(zhuǎn)換成二進(jìn)制并返回。
>>> bin(3)
'0b11'
>>> bin(-10)
'-0b1010'
oct:將十進(jìn)制轉(zhuǎn)化成八進(jìn)制字符串并返回。
>>> oct(8)
'0o10'
>>> oct(-56)
'-0o70'
hex:將十進(jìn)制轉(zhuǎn)化成十六進(jìn)制字符串并返回。
>>> hex(255)
'0xff'
>>> hex(-42)
'-0x2a'
數(shù)學(xué)運(yùn)算(7):
abs:函數(shù)返回?cái)?shù)字的絕對(duì)值。
>>> abs(-20)
20
>>> abs(-28.33)
28.33
divmod:計(jì)算除數(shù)與被除數(shù)的結(jié)果,返回一個(gè)包含商和余數(shù)的元組(a // b, a % b),可以用到頁(yè)碼的計(jì)算。
>>> divmod(2.4, 1.1)
(2.0, 0.19999999999999973)
>>> divmod(33, 15)
(2, 3)
>>>
round:保留浮點(diǎn)數(shù)的小數(shù)位數(shù),默認(rèn)保留整數(shù)。
>>> round(0.5)
0
>>> round(1.5)
2
## if two multiples are equally close, rounding is done toward the even choice ## (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2).
pow:求xy次冪。(三個(gè)參數(shù)為xy的結(jié)果對(duì)z取余)
>>> pow(3, -2, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: pow() 2nd argument cannot be negative when 3rd argument specified
>>> pow(3, 2, 7)
2
sum:對(duì)可迭代對(duì)象進(jìn)行求和計(jì)算(可設(shè)置初始值)。
>>> sum([1,2,3,4], 10)
20
min:返回可迭代對(duì)象的最小值(可加key,key為函數(shù)名,通過(guò)函數(shù)的規(guī)則,返回最小值)。 key可以跟lambda函數(shù)用。
>>> min([-1, 3, 4, 9, -10])
-10
>>> min([-1, 3, 4, 9, -10], key=abs)
-1
max:返回可迭代對(duì)象的最大值(可加key,key為函數(shù)名,通過(guò)函數(shù)的規(guī)則,返回最大值)。key可以跟lambda函數(shù)用。
>>> max([-1, 3, 4, 9, -10])
9
>>> max([-1, 3, 4, 9, -10], key=abs)
-10
和數(shù)據(jù)結(jié)構(gòu)相關(guān)
列表和元祖(2)
list:將一個(gè)可迭代對(duì)象轉(zhuǎn)化成列表(如果是字典,默認(rèn)將key作為列表的元素)。
>>> list({'a':1, 'b':3})
['a', 'b']
tuple:將一個(gè)可迭代對(duì)象轉(zhuǎn)化成元祖(如果是字典,默認(rèn)將key作為元祖的元素)。
相關(guān)內(nèi)置函數(shù)(2)
reversed:將一個(gè)序列翻轉(zhuǎn),并返回此翻轉(zhuǎn)序列的迭代器。
>>> reversed([3,1,6,4,9]) ## Return a reverse iterator.
<list_reverseiterator object at 0x000001B2B4258E80>
>>> list(reversed([3,1,6,4,9]))
[9, 4, 6, 1, 3]
slice:構(gòu)造一個(gè)切片對(duì)象,用于列表的切片。
>>> li = ['a','b','c','d','e','f','g']
>>> li[slice(3)]
['a', 'b', 'c']
>>> li[slice(1, 3)]
['b', 'c']
>>> li[slice(1, None, 2)]
['b', 'd', 'f']
>>> li[slice(1, None, 1)]
['b', 'c', 'd', 'e', 'f', 'g']
字符串相關(guān)(9)
str:將數(shù)據(jù)轉(zhuǎn)化成字符串。
class str(object='')
class str(object=b'', encoding='utf-8', errors='strict')
Return a string version of object. If object is not provided, returns the empty string. Otherwise, the behavior of str() depends on whether encoding or errors is given, as follows.
If neither encoding nor errors is given, str(object) returns object.__str__(), which is the “informal” or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a __str__() method, then str() falls back to returning repr(object).
If at least one of encoding or errors is given, object should be a bytes-like object (e.g. bytes or bytearray). In this case, if object is a bytes (or bytearray) object, then str(bytes, encoding, errors) is equivalent to bytes.decode(encoding, errors). Otherwise, the bytes object underlying the buffer object is obtained before calling bytes.decode(). See Binary Sequence Types — bytes, bytearray, memoryview and Buffer Protocol for information on buffer objects.
Passing a bytes object to str() without the encoding or errors arguments falls under the first case of returning the informal string representation (see also the -b command-line option to Python). For example:
>>>
>>> str(b'Zoot!')
"b'Zoot!'"
format:與具體數(shù)據(jù)相關(guān),用于計(jì)算各種小數(shù),精算等?!铩铩睢睢?/h6>
>>> format('text', '<20')
'text '
>>> format('text', '>20')
' text'
>>> format('text', '^20')
' text '
bytes:用于不同編碼之間的轉(zhuǎn)化。 ★★★★☆
>>> format('text', '<20')
'text '
>>> format('text', '>20')
' text'
>>> format('text', '^20')
' text '
unicode ---> bytes 類(lèi)型
>>> sz = '深圳'
>>> sz.encode('utf-8')
b'\xe6\xb7\xb1\xe5\x9c\xb3'
>>> bytes(sz,encoding='utf-8')
b'\xe6\xb7\xb1\xe5\x9c\xb3'
>>> _ == sz.encode('utf-8')
True
bytearry:返回一個(gè)新字節(jié)數(shù)組。這個(gè)數(shù)組里的元素是可變的,并且每個(gè)元素的值范圍: 0 <= x < 256。
>>> ret = bytearray('python', encoding='utf-8')
>>> ret
bytearray(b'python')
>>> id(ret)
1337379950296
>>> ret[0]
112
>>> ret
bytearray(b'python')
>>> id(ret)
1337379950296
memoryview
>>> ret = memoryview(bytes('你好', encoding='utf-8'))
>>> ret
<memory at 0x00000137620F6048>
>>> len(ret)
6
>>> bytes(ret[:3]).decode('utf-8')
'你'
>>> bytes(ret[3:]).decode('utf-8')
'好'
ord:輸入字符找該字符編碼 unicode 的位置
>>> ord('x')
120
>>> ord('好')
22909
chr:輸入位置數(shù)字找出其對(duì)應(yīng)的字符 unicode
>>> chr(120)
'x'
>>> chr(22909)
'好'
ascii:是ascii碼中的返回該值,不是則返回他在unicode的位置(16進(jìn)制。)
>>> ascii('x')
"'x'"
>>> ascii('好')
"'\\u597d'"
>>> ascii(120)
'120'
>>> ascii('x好')
"'x\\u597d'"
repr:返回一個(gè)對(duì)象的string形式(原形畢露)?!铩铩铩?/h6>
>>> 'python'
'python'
>>> repr('python')
"'python'"
>>> '你是個(gè)%r人' % '好' # 格式化輸出 %r
"你是個(gè)'好'人"
數(shù)據(jù)集合(3)
dict:創(chuàng)建一個(gè)字典。
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
set:創(chuàng)建一個(gè)集合。
>>> set('abc')
{'c', 'b', 'a'}
frozenset:返回一個(gè)凍結(jié)的集合,凍結(jié)后集合不能再添加或刪除任何元素。
>>> frozenset('abc')
frozenset({'c', 'b', 'a'})
>>> hash(_)
-76181078804554994
>>> set('abc')
{'c', 'b', 'a'}
>>> hash(_)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
相關(guān)內(nèi)置函數(shù)(8)
len:返回一個(gè)對(duì)象中元素的個(gè)數(shù)。
sorted:對(duì)所有可迭代的對(duì)象進(jìn)行排序操作?!铩铩铩铩?/h6>
>>> l1 = [2,3,5,3,1,9,8,6]
>>> l1.sort() 形成了一個(gè)新列表
>>> l1
[1, 2, 3, 3, 5, 6, 8, 9]
>>> l1 = [2,3,5,3,1,9,8,6]
>>> sorted(l1)
[1, 2, 3, 3, 5, 6, 8, 9]
>>> l1
[2,3,5,3,1,9,8,6] # 原列表不變
sorted(iterable, *, key=None, reverse=False) # ------> pass
enumerate:枚舉,返回一個(gè)枚舉對(duì)象。 第二參數(shù)為開(kāi)始計(jì)數(shù)
>>> enumerate([1,2,3])
<enumerate object at 0x00000137620ED678>
>>> for i in _:
... print(i)
...
(0, 1)
(1, 2)
(2, 3)
>>> enumerate([1,2,3])
<enumerate object at 0x00000137620ED750>
>>> for index, i in _:
... print(index, i)
...
0 1
1 2
2 3
all:可迭代對(duì)象中,全都是True才是True
>>> all([0, 2])
False
>>> all([1, 2])
True
any:可迭代對(duì)象中,有一個(gè)True 就是True
>>> any([1, 0])
True
>>> any(['', 0])
False
zip:
>>> 'python'
'python'
>>> repr('python')
"'python'"
>>> '你是個(gè)%r人' % '好' # 格式化輸出 %r
"你是個(gè)'好'人"
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
>>> set('abc')
{'c', 'b', 'a'}
>>> frozenset('abc')
frozenset({'c', 'b', 'a'})
>>> hash(_)
-76181078804554994
>>> set('abc')
{'c', 'b', 'a'}
>>> hash(_)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
>>> l1 = [2,3,5,3,1,9,8,6]
>>> l1.sort() 形成了一個(gè)新列表
>>> l1
[1, 2, 3, 3, 5, 6, 8, 9]
>>> l1 = [2,3,5,3,1,9,8,6]
>>> sorted(l1)
[1, 2, 3, 3, 5, 6, 8, 9]
>>> l1
[2,3,5,3,1,9,8,6] # 原列表不變
sorted(iterable, *, key=None, reverse=False) # ------> pass
enumerate:枚舉,返回一個(gè)枚舉對(duì)象。 第二參數(shù)為開(kāi)始計(jì)數(shù)
>>> enumerate([1,2,3])
<enumerate object at 0x00000137620ED678>
>>> for i in _:
... print(i)
...
(0, 1)
(1, 2)
(2, 3)
>>> enumerate([1,2,3])
<enumerate object at 0x00000137620ED750>
>>> for index, i in _:
... print(index, i)
...
0 1
1 2
2 3
all:可迭代對(duì)象中,全都是True才是True
>>> all([0, 2])
False
>>> all([1, 2])
True
any:可迭代對(duì)象中,有一個(gè)True 就是True
>>> any([1, 0])
True
>>> any(['', 0])
False
zip:
函數(shù)用于將可迭代的對(duì)象作為參數(shù),將對(duì)象中對(duì)應(yīng)的元素打包成一個(gè)個(gè)元組,然后返回由這些元組組成的列表。如果各個(gè)迭代器的元素個(gè)數(shù)不一致,則返回列表長(zhǎng)度與最短的對(duì)象相同。
>>> l1 = [1,2,3,4,5,6,7]
>>> tu1 = ('a','b', 'c', 'd')
>>> dic = {'name':'python', 'price':9999}
>>> zip(l1, tu1, dic)
<zip object at 0x00000137620F1548>
>>> list(_)
[(1, 'a', 'name'), (2, 'b', 'price')]
filter:過(guò)濾·。
>>> l1 = [1, 2, 3, 4, 5, 6, 7, 8]
>>> filter(lambda x:x % 2, l1)
<filter object at 0x00000137620F70B8>
>>> list(_)
[1, 3, 5, 7]
map:會(huì)根據(jù)提供的函數(shù)對(duì)指定序列做映射。
>>> l1 = [1, 2, 3, 4, 5, 6, 7, 8]
>>> map(lambda x:x**2, l1)
<map object at 0x00000137620F7128>
>>> list(_)
[1, 4, 9, 16, 25, 36, 49, 64]
匿名函數(shù)
函數(shù)名 = lambda 參數(shù) :返回值
#參數(shù)可以有多個(gè),用逗號(hào)隔開(kāi)
#匿名函數(shù)不管邏輯多復(fù)雜,只能寫(xiě)一行,且邏輯執(zhí)行結(jié)束后的內(nèi)容就是返回值
#返回值和正常的函數(shù)一樣可以是任意數(shù)據(jù)類(lèi)型