<
德安網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián)建站,德安網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為德安上千余家提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\
成都外貿(mào)網(wǎng)站建設(shè)要多少錢,請(qǐng)找那個(gè)售后服務(wù)好的
德安做網(wǎng)站的公司定做!a target="_blank">建站服務(wù)器
三元運(yùn)算(三目運(yùn)算),是對(duì)簡單的條件語句的縮寫。
# 書寫格式
result = 值1 if 條件 else 值2
# 如果條件成立,那么將 “值1” 賦值給result變量,否則,將“值2”賦值給result變量
基本數(shù)據(jù)類型補(bǔ)充
set
set集合,是一個(gè)無序且不重復(fù)的元素集合
class set(object):
set() -> new empty set object
set(iterable) -> new set object
Build an unordered collection of unique elements.
def add(self, *args, **kwargs): # real signature unknown
Add an element to a set,添加元素
This has no effect if the element is already present.
pass
def clear(self, *args, **kwargs): # real signature unknown
Remove all elements from this set. 清除內(nèi)容
pass
def copy(self, *args, **kwargs): # real signature unknown
Return a shallow copy of a set. 淺拷貝
pass
def difference(self, *args, **kwargs): # real signature unknown
Return the difference of two or more sets as a new set. A中存在,B中不存在
(i.e. all elements that are in this set but not the others.)
pass
def difference_update(self, *args, **kwargs): # real signature unknown
Remove all elements of another set from this set. 從當(dāng)前集合中刪除和B中相同的元素
pass
def discard(self, *args, **kwargs): # real signature unknown
Remove an element from a set if it is a member.
If the element is not a member, do nothing. 移除指定元素,不存在不保錯(cuò)
pass
def intersection(self, *args, **kwargs): # real signature unknown
Return the intersection of two sets as a new set. 交集
(i.e. all elements that are in both sets.)
pass
def intersection_update(self, *args, **kwargs): # real signature unknown
Update a set with the intersection of itself and another. 取交集并更更新到A中
pass
def isdisjoint(self, *args, **kwargs): # real signature unknown
Return True if two sets have a null intersection. 如果沒有交集,返回True,否則返回False
pass
def issubset(self, *args, **kwargs): # real signature unknown
Report whether another set contains this set. 是否是子序列
pass
def issuperset(self, *args, **kwargs): # real signature unknown
Report whether this set contains another set. 是否是父序列
pass
def pop(self, *args, **kwargs): # real signature unknown
Remove and return an arbitrary set element.
Raises KeyError if the set is empty. 移除元素
pass
def remove(self, *args, **kwargs): # real signature unknown
Remove an element from a set; it must be a member.
If the element is not a member, raise a KeyError. 移除指定元素,不存在保錯(cuò)
pass
def symmetric_difference(self, *args, **kwargs): # real signature unknown
Return the symmetric difference of two sets as a new set. 對(duì)稱差集
(i.e. all elements that are in exactly one of the sets.)
pass
def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
Update a set with the symmetric difference of itself and another. 對(duì)稱差集,并更新到a中
pass
def union(self, *args, **kwargs): # real signature unknown
Return the union of sets as a new set. 并集
(i.e. all elements that are in either set.)
pass
def update(self, *args, **kwargs): # real signature unknown
Update a set with the union of itself and others. 更新
pass
練習(xí):尋找差異
# 數(shù)據(jù)庫中原有
old_dict = {
#1:{ \'hostname\':c1, \'cpu_count\': 2, \'mem_capicity\': 80 },
#2:{ \'hostname\':c1, \'cpu_count\': 2, \'mem_capicity\': 80 }
#3:{ \'hostname\':c1, \'cpu_count\': 2, \'mem_capicity\': 80 }
}
# cmdb 新匯報(bào)的數(shù)據(jù)
new_dict = {
#1:{ \'hostname\':c1, \'cpu_count\': 2, \'mem_capicity\': 800 },
#3:{ \'hostname\':c1, \'cpu_count\': 2, \'mem_capicity\': 80 }
#4:{ \'hostname\':c2, \'cpu_count\': 2, \'mem_capicity\': 80 }
}
需要?jiǎng)h除:?
需要新建:?
需要更新:?
注意:無需考慮內(nèi)部元素是否改變,只要原來存在,新匯報(bào)也存在,就是需要更新
深淺拷貝
一、數(shù)字和字符串
對(duì)于 數(shù)字 和 字符串 而言,賦值、淺拷貝和深拷貝無意義,因?yàn)槠溆肋h(yuǎn)指向同一個(gè)內(nèi)存地址。
import copy
# ######### 數(shù)字、字符串 #########
n1 = 123
# n1 = i am alex age 10
print(id(n1))
# ## 賦值 ##
n2 = n1
print(id(n2))
# ## 淺拷貝 ##
n2 = copy.copy(n1)
print(id(n2))
# ## 深拷貝 ##
n3 = copy.deepcopy(n1)
print(id(n3))
二、其他基本數(shù)據(jù)類型
對(duì)于字典、元祖、列表 而言,進(jìn)行賦值、淺拷貝和深拷貝時(shí),其內(nèi)存地址的變化是不同的。
1、賦值
賦值,只是創(chuàng)建一個(gè)變量,該變量指向原來內(nèi)存地址,如:
n1 = {k1: wu, k2: 123, k3: [alex, 456]}
n2 = n1
2、淺拷貝
淺拷貝,在內(nèi)存中只額外創(chuàng)建第一層數(shù)據(jù)
import copy
n1 = {k1: wu, k2: 123, k3: [alex, 456]}
n3 = copy.copy(n1)
3、深拷貝
深拷貝,在內(nèi)存中將所有的數(shù)據(jù)重新創(chuàng)建一份(排除最后一層,即:python內(nèi)部對(duì)字符串和數(shù)字的優(yōu)化)
import copy
n1 = {k1: wu, k2: 123, k3: [alex, 456]}
n4 = copy.deepcopy(n1)
函數(shù)
一、背景
在學(xué)習(xí)函數(shù)之前,一直遵循:面向過程編程,即:根據(jù)業(yè)務(wù)邏輯從上到下實(shí)現(xiàn)功能,其往往用一長段代碼來實(shí)現(xiàn)指定功能,開發(fā)過程中最常見的操作就是粘貼復(fù)制,也就是將之前實(shí)現(xiàn)的代碼塊復(fù)制到現(xiàn)需功能處,如下:
while True:
if cpu利用率 > 90%:
#發(fā)送郵件提醒
連接郵箱服務(wù)器
發(fā)送郵件
關(guān)閉連接
if 硬盤使用空間 > 90%:
#發(fā)送郵件提醒
連接郵箱服務(wù)器
發(fā)送郵件
關(guān)閉連接
if 內(nèi)存占用 > 80%:
#發(fā)送郵件提醒
連接郵箱服務(wù)器
發(fā)送郵件
關(guān)閉連接
腚眼一看上述代碼,if條件語句下的內(nèi)容可以被提取出來公用,如下:
def 發(fā)送郵件(內(nèi)容)
#發(fā)送郵件提醒
連接郵箱服務(wù)器
發(fā)送郵件
關(guān)閉連接
while True:
if cpu利用率 > 90%:
發(fā)送郵件(\'CPU報(bào)警\')
if 硬盤使用空間 > 90%:
發(fā)送郵件(\'硬盤報(bào)警\')
if 內(nèi)存占用 > 80%:
對(duì)于上述的兩種實(shí)現(xiàn)方式,第二次必然比第一次的重用性和可讀性要好,其實(shí)這就是函數(shù)式編程和面向過程編程的區(qū)別:
函數(shù)式:將某功能代碼封裝到函數(shù)中,日后便無需重復(fù)編寫,僅調(diào)用函數(shù)即可
面向?qū)ο螅簩?duì)函數(shù)進(jìn)行分類和封裝,讓開發(fā)“更快更好更強(qiáng)...”
函數(shù)式編程最重要的是增強(qiáng)代碼的重用性和可讀性
二、定義和使用
def 函數(shù)名(參數(shù)):
...
函數(shù)體
...
返回值
函數(shù)的定義主要有如下要點(diǎn):
def:表示函數(shù)的關(guān)鍵字
函數(shù)名:函數(shù)的名稱,日后根據(jù)函數(shù)名調(diào)用函數(shù)
函數(shù)體:函數(shù)中進(jìn)行一系列的邏輯計(jì)算,如:發(fā)送郵件、計(jì)算出 [11,22,38,888,2]中的數(shù)等...
參數(shù):為函數(shù)體提供數(shù)據(jù)
返回值:當(dāng)函數(shù)執(zhí)行完畢后,可以給調(diào)用者返回?cái)?shù)據(jù)。
1、返回值
函數(shù)是一個(gè)功能塊,該功能到底執(zhí)行成功與否,需要通過返回值來告知調(diào)用者。
以上要點(diǎn)中,比較重要有參數(shù)和返回值:
def 發(fā)送短信():
發(fā)送短信的代碼...
if 發(fā)送成功:
return True
else:
return False
while True:
# 每次執(zhí)行發(fā)送短信函數(shù),都會(huì)將返回值自動(dòng)賦值給result
# 之后,可以根據(jù)result來寫日志,或重發(fā)等操作
result = 發(fā)送短信()
if result == False:
記錄日志,短信發(fā)送失敗...
2、參數(shù)
為什么要有參數(shù)?
def CPU報(bào)警郵件()
#發(fā)送郵件提醒
連接郵箱服務(wù)器
發(fā)送郵件
關(guān)閉連接
def 硬盤報(bào)警郵件()
#發(fā)送郵件提醒
連接郵箱服務(wù)器
發(fā)送郵件
關(guān)閉連接
def 內(nèi)存報(bào)警郵件()
#發(fā)送郵件提醒
連接郵箱服務(wù)器
發(fā)送郵件
關(guān)閉連接
while True:
if cpu利用率 > 90%:
CPU報(bào)警郵件()
if 硬盤使用空間 > 90%:
硬盤報(bào)警郵件()
if 內(nèi)存占用 > 80%:
內(nèi)存報(bào)警郵件()
def 發(fā)送郵件(郵件內(nèi)容)
#發(fā)送郵件提醒
連接郵箱服務(wù)器
發(fā)送郵件
關(guān)閉連接
while True:
if cpu利用率 > 90%:
發(fā)送郵件(CPU報(bào)警了。)
if 硬盤使用空間 > 90%:
發(fā)送郵件(硬盤報(bào)警了。)
if 內(nèi)存占用 > 80%:
發(fā)送郵件(內(nèi)存報(bào)警了。)
有參數(shù)實(shí)現(xiàn)
函數(shù)的有三中不同的參數(shù):
普通參數(shù)
# ######### 定義函數(shù) #########
# name 叫做函數(shù)func的形式參數(shù),簡稱:形參
def func(name):
print name
# ######### 執(zhí)行函數(shù) #########
# \'wupeiqi\' 叫做函數(shù)func的實(shí)際參數(shù),簡稱:實(shí)參
func(\'wupeiqi\')
默認(rèn)參數(shù)
def func(name, age = 18):
print %s:%s %(name,age)
# 指定參數(shù)
func(\'wupeiqi\', 19)
# 使用默認(rèn)參數(shù)
func(\'alex\')
注:默認(rèn)參數(shù)需要放在參數(shù)列表最后
動(dòng)態(tài)參數(shù)
def func(*args):
print args
# 執(zhí)行方式一
func(11,33,4,4454,5)
# 執(zhí)行方式二
li = [11,2,2,3,3,4,54]
func(*li)
def func(*args, **kwargs):
print args
print kwargs
擴(kuò)展:發(fā)送郵件實(shí)例
發(fā)送郵件實(shí)例
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
msg = MIMEText(\'郵件內(nèi)容\', \'plain\', \'utf-8\')
msg[\'From\'] = formataddr([武沛齊,\'wptawy@126.com\'])
msg[\'To\'] = formataddr([走人,\'424662508@qq.com\'])
msg[\'Subject\'] = 主題
server = smtplib.SMTP(smtp.126.com, 25)
server.login(wptawy@126.com, 郵箱密碼)
server.sendmail(\'wptawy@126.com\', [\'424662508@qq.com\',], msg.as_string())
server.quit()
內(nèi)置函數(shù)
注:查看詳細(xì)猛擊這里
open函數(shù),該函數(shù)用于文件處理
操作文件時(shí),一般需要經(jīng)歷如下步驟:
打開文件
操作文件
一、打開文件
文件句柄 = open(\'文件路徑\', \'模式\')
打開文件時(shí),需要指定文件路徑和以何等方式打開文件,打開后,即可獲取該文件句柄,日后通過此文件句柄對(duì)該文件操作。
打開文件的模式有:
r ,只讀模式【默認(rèn)】
w,只寫模式【不可讀;不存在則創(chuàng)建;存在則清空內(nèi)容;】
x, 只寫模式【不可讀;不存在則創(chuàng)建,存在則報(bào)錯(cuò)】
a, 追加模式【可讀; 不存在則創(chuàng)建;存在則只追加內(nèi)容;】
+ 表示可以同時(shí)讀寫某個(gè)文件
r+, 讀寫【可讀,可寫】
w+,寫讀【可讀,可寫】
x+ ,寫讀【可讀,可寫】
a+, 寫讀【可讀,可寫】
b表示以字節(jié)的方式操作
rb 或 r+b
wb 或 w+b
xb 或 w+b
ab 或 a+b
注:以b方式打開時(shí),讀取到的內(nèi)容是字節(jié)類型,寫入時(shí)也需要提供字節(jié)類型
二、操作
2.
class file(object)
def close(self): # real signature unknown; restored from __doc__
關(guān)閉文件
close() -> None or (perhaps) an integer. Close the file.
Sets data attribute .closed to True. A closed file cannot be used for
further I/O operations. close() may be called more than once without
error. Some kinds of file objects (for example, opened by popen())
may return an exit status upon closing.
def fileno(self): # real signature unknown; restored from __doc__
文件描述符
fileno() -> integer file descriptor.
This is needed for lower-level file interfaces, such os.read().
return 0
def flush(self): # real signature unknown; restored from __doc__
刷新文件內(nèi)部緩沖區(qū)
flush() -> None. Flush the internal I/O buffer.
pass
def isatty(self): # real signature unknown; restored from __doc__
判斷文件是否是同意tty設(shè)備
isatty() -> true or false. True if the file is connected to a tty device.
return False
def next(self): # real signature unknown; restored from __doc__
獲取下一行數(shù)據(jù),不存在,則報(bào)錯(cuò)
x.next() -> the next value, or raise StopIteration
pass
def read(self, size=None): # real signature unknown; restored from __doc__
讀取指定字節(jié)數(shù)據(jù)
read([size]) -> read at most size bytes, returned as a string.
If the size argument is negative or omitted, read until EOF is reached.
Notice that when in non-blocking mode, less data than what was requested
may be returned, even if no size parameter was given.
pass
def readinto(self): # real signature unknown; restored from __doc__
讀取到緩沖區(qū),不要用,將被遺棄
readinto() -> Undocumented. Don\'t use this; it may go away.
pass
def readline(self, size=None): # real signature unknown; restored from __doc__
僅讀取一行數(shù)據(jù)
readline([size]) -> next line from the file, as a string.
Retain newline. A non-negative size argument limits the maximum
number of bytes to return (an incomplete line may be returned then).
Return an empty string at EOF.
pass
def readlines(self, size=None): # real signature unknown; restored from __doc__
讀取所有數(shù)據(jù),并根據(jù)換行保存值列表
readlines([size]) -> list of strings, each a line from the file.
Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the
total number of bytes in the lines returned.
return []
def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
指定文件中指針位置
seek(offset[, whence]) -> None. Move to new file position.
Argument offset is a byte count. Optional argument whence defaults to
(offset from start of file, offset should be >= 0); other values are 1
(move relative to current position, positive or negative), and 2 (move
relative to end of file, usually negative, although many platforms allow
seeking beyond the end of a file). If the file is opened in text mode,
only offsets returned by tell() are legal. Use of other offsets causes
undefined behavior.
Note that not all file objects are seekable.
pass
def tell(self): # real signature unknown; restored from __doc__
獲取當(dāng)前指針位置
tell() -> current file position, an integer (may be a long integer).
pass
def truncate(self, size=None): # real signature unknown; restored from __doc__
截?cái)鄶?shù)據(jù),僅保留指定之前數(shù)據(jù)
truncate([size]) -> None. Truncate the file to at most size bytes.
Size defaults to the current file position, as returned by tell().
pass
def write(self, p_str): # real signature unknown; restored from __doc__
寫內(nèi)容
write(str) -> None. Write string str to file.
Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.
pass
def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
將一個(gè)字符串列表寫入文件
writelines(sequence_of_strings) -> None. Write the strings to the file.
Note that newlines are not added. The sequence can be any iterable object
producing strings. This is equivalent to calling write() for each string.
pass
def xreadlines(self): # real signature unknown; restored from __doc__
可用于逐行讀取文件,非全部
xreadlines() -> returns self.
For backward compatibility. File objects now include the performance
optimizations previously implemented in the xreadlines module.
pass
復(fù)制代碼
復(fù)制代碼
class TextIOWrapper(_TextIOBase):
Character and line based layer over a BufferedIOBase object, buffer.
encoding gives the name of the encoding that the stream will be
decoded or encoded with. It defaults to locale.getpreferredencoding(False).
errors determines the strictness of encoding and decoding (see
help(codecs.Codec) or the documentation for codecs.register) and
defaults to strict.
newline controls how line endings are handled. It can be None, \'\',
\'\\n\', \'\\r\', and \'\\r\\n\'. It works as follows:
* On input, if newline is None, universal newlines mode is
enabled. Lines in the input can end in \'\\n\', \'\\r\', or \'\\r\\n\', and
these are translated into \'\\n\' before being returned to the
caller. If it is \'\', universal newline mode is enabled, but line
endings are returned to the caller untranslated. If it has any of
the other legal values, input lines are only terminated by the given
string, and the line ending is returned to the caller untranslated.
* On output, if newline is None, any \'\\n\' characters written are
translated to the system default line separator, os.linesep. If
newline is \'\' or \'\\n\', no translation takes place. If newline is any
of the other legal values, any \'\\n\' characters written are translated
to the given string.
If line_buffering is True, a call to flush is implied when a call to
write contains a newline character.
def close(self, *args, **kwargs): # real signature unknown
關(guān)閉文件
pass
def fileno(self, *args, **kwargs): # real signature unknown
文件描述符
pass
def flush(self, *args, **kwargs): # real signature unknown
刷新文件內(nèi)部緩沖區(qū)
pass
def isatty(self, *args, **kwargs): # real signature unknown
判斷文件是否是同意tty設(shè)備
pass
def read(self, *args, **kwargs): # real signature unknown
讀取指定字節(jié)數(shù)據(jù)
pass
def readable(self, *args, **kwargs): # real signature unknown
是否可讀
pass
def readline(self, *args, **kwargs): # real signature unknown
僅讀取一行數(shù)據(jù)
pass
def seek(self, *args, **kwargs): # real signature unknown
指定文件中指針位置
pass
def seekable(self, *args, **kwargs): # real signature unknown
指針是否可操作
pass
def tell(self, *args, **kwargs): # real signature unknown
獲取指針位置
pass
def truncate(self, *args, **kwargs): # real signature unknown
截?cái)鄶?shù)據(jù),僅保留指定之前數(shù)據(jù)
pass
def writable(self, *args, **kwargs): # real signature unknown
是否可寫
pass
def write(self, *args, **kwargs): # real signature unknown
寫內(nèi)容
pass
def __getstate__(self, *args, **kwargs): # real signature unknown
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
Create and return a new object. See help(type) for accurate signature.
pass
def __next__(self, *args, **kwargs): # real signature unknown
Implement next(self).
pass
def __repr__(self, *args, **kwargs): # real signature unknown
Return repr(self).
pass
buffer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
closed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
errors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
newlines = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
_CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
_finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
3.x
三、管理上下文
為了避免打開文件后忘記關(guān)閉,可以通過管理上下文,即:
with open(\'log\',\'r\') as f:
...
如此方式,當(dāng)with代碼塊執(zhí)行完畢時(shí),內(nèi)部會(huì)自動(dòng)關(guān)閉并釋放文件資源。
在Python 2.7 及以后,with又支持同時(shí)對(duì)多個(gè)文件的上下文進(jìn)行管理,即:
with open(\'log1\') as obj1, open(\'log2\') as obj2:
pass
lambda表達(dá)式
學(xué)習(xí)條件運(yùn)算時(shí),對(duì)于簡單的 if else 語句,可以使用三元運(yùn)算來表示,即:
# 普通條件語句
if 1 == 1:
name = \'wupeiqi\'
else:
name = \'alex\'
# 三元運(yùn)算
name = \'wupeiqi\' if 1 == 1 else \'alex\'
對(duì)于簡單的函數(shù),也存在一種簡便的表示方式,即:lambda表達(dá)式
# ###################### 普通函數(shù) ######################
# 定義函數(shù)(普通方式)
def func(arg):
return arg + 1
# 執(zhí)行函數(shù)
result = func(123)
# ###################### lambda ######################
# 定義函數(shù)(lambda表達(dá)式)
my_lambda = lambda arg : arg + 1
# 執(zhí)行函數(shù)
result = my_lambda(123)
遞歸
利用函數(shù)編寫如下數(shù)列:
斐波那契數(shù)列指的是這樣一個(gè)數(shù)列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368...
def func(arg1,arg2):
if arg1 == 0:
print arg1, arg2
arg3 = arg1 + arg2
print arg3
func(arg2, arg3)
func(0,1)
練習(xí)題
1、簡述普通參數(shù)、指定參數(shù)、默認(rèn)參數(shù)、動(dòng)態(tài)參數(shù)的區(qū)別
2、寫函數(shù),計(jì)算傳入字符串中【數(shù)字】、【字母】、【空格] 以及 【其他】的個(gè)數(shù)
3、寫函數(shù),判斷用戶傳入的對(duì)象(字符串、列表、元組)長度是否大于5。
4、寫函數(shù),檢查用戶傳入的對(duì)象(字符串、列表、元組)的每一個(gè)元素是否含有空內(nèi)容。
5、寫函數(shù),檢查傳入列表的長度,如果大于2,那么僅保留前兩個(gè)長度的內(nèi)容,并將新內(nèi)容返回給調(diào)用者。
6、寫函數(shù),檢查獲取傳入列表或元組對(duì)象的所有奇數(shù)位索引對(duì)應(yīng)的元素,并將其作為新列表返回給調(diào)用者。
7、寫函數(shù),檢查傳入字典的每一個(gè)value的長度,如果大于2,那么僅保留前兩個(gè)長度的內(nèi)容,并將新內(nèi)容返回給調(diào)用者。
dic = {k1: v1v1, k2: [11,22,33,44]}
PS:字典中的value只能是字符串或列表
8、寫函數(shù),利用遞歸獲取斐波那契數(shù)列中的第 10 個(gè)數(shù),并將該值返回給調(diào)用者。
當(dāng)前標(biāo)題:python基礎(chǔ)之函數(shù)
文章源于:
http://weahome.cn/article/cpcidj.html