Python 基礎部分-3

Set 集合html

set集合,是一個無序並且不重複的元素集合python

list ==> 容許重複的集合,可修改git

tuple ==>容許重複的集合,不可修改程序員

dict ==> 容許重複的集合,可修改數據庫

set ==> 不容許重複的集合(不容許重複的列表)express

 

建立集合api

s = set()數組

s = set()
s.add(11)
s.add(11)
s.add(11)
print(s)
>>>{11}

s.add(22)
print(s)
>>> {11, 22}

s = { }app

>>> s = {11, 22, 33, 11}
>>> print(s)
{33, 11, 22}
>>> type(s)
<class 'set'>

 

轉換集合less

s = set([ ])

s = set(( ))

s = set({ })

l = [11,22,11,33]#列表轉換成集合
s1 = set()
s2 = set(l)
print(s2)
>>>{33, 11, 22}

 

set的基本功能

set.add()

se = set()
print(se)
>>> set()
se.add(44)#增長一個元素 print(se)
>>> {44}

set.clear()

se = {11,22,33}
type(se)
>>> <class 'set'>
se.clear()#清空集合內容 print(se)
>>> set()

set.difference()

>>> se = {11,22,33}
>>> be = {22,55}
>>> se.difference(be)#查找se中存在的, 但be不存在的集合, 並賦值給新的變量
{33, 11} #刪除共有的元素,並把刪除的元素賦值給變量


>>> be.difference(se)
>>> {55}

 >>> ret = be.difference(se)
 >>> print(ret)
 {55}

set.difference_update()

>>> se = {11,22,33}
>>> be = {33,55,66}
>>> se.difference_update(be) #查找se中存在, 但be不存在的元素,並更新集合
>>> print(se)

{11, 22} #刪除共有的元素,並更新集合

difference        A中存在,B不存在(除去交集),返回一個新的值,由變量接收

difference_update    A中存在,B不存在(除去交集),跟新A

 

set.discard() 

set.remove()

set.pop()

>>>se = {11,22,33}
>>>se.discard(11)
>>>print(se)

{33, 22}

>>>se = {11,22,33}
>>>se.remove(11)
>>>print(se)

{33, 22}

>>> se = {11,22,33,44}
>>> ret = se.pop() #因爲set是無序的集合,可視爲隨機刪除元素
>>> print(ret)
33
>>> print(se)

{11, 44, 22}

set.intersection()

se = {11,22,33}
be = {22,95, "隨便"}
ret = se.intersection(be)
print(ret)

>>>{22}

set.intersection_update()

se = {11,22,33}
be = {22,95, "隨便"}

se.intersection_update(be)
print(se)

>>>{22}

set.isdisjoint()

se = {11,22,33}
be = {33,44,55,66,77}
ret = se.isdisjoint(be) #是否有非交集
print(ret)

>>> False #有交集爲False, 沒交集爲True

set.issubset()

se = {22,33,}
be = {11,22,33}
ret = se.issubset(be)#是否子集 print(ret)

>>>True

set.issuperset()

se = {11,22,33,44}
be = {11,22}
ret = se.issuperset(be)#是否父集
print(ret)
>>>Ture

set.symmetric_difference()

se = {11,22,33,44}
be = {11,22,77,55}

ret = se.symmetric_difference(be) #兩集合的差集 print(ret)

>>>{33,44,77,55}

set.symmetric_difference_update()

se = {11,22,33,44}
be = {11,22,77,55}

se.symmetric_difference_update(be) #更新se爲兩集合的差集 print(se)

>>>{33,44,77,55}

set.union()

se = {11,22,33,44}
be = {11,22,77,55}

ret = se.union(be) #並集
print(ret)

>>>{11,22,33,44,55,77}

set.update()

se = {11,22,33,44,55}
be = {11,22,66,77}
se.update(be)
print(se)
>>> {33, 66, 11, 44, 77, 22, 55}

se.update([111,222,333])
print(se)

>>>{33, 66, 11, 44, 77, 333, 111, 22, 55, 222}

集合的源碼

  1 class set(object):
  2 
  3     """
  4 
  5     set() -> new empty set object
  6 
  7     set(iterable) -> new set object
  8 
  9      
 10 
 11     Build an unordered collection of unique elements.
 12 
 13     """
 14 
 15     def add(self, *args, **kwargs): # real signature unknown
 16 
 17         """
 18 
 19         Add an element to a set,添加元素
 20 
 21          
 22 
 23         This has no effect if the element is already present.
 24 
 25         """
 26 
 27         pass
 28 
 29  
 30 
 31     def clear(self, *args, **kwargs): # real signature unknown
 32 
 33         """ Remove all elements from this set. 清楚內容"""
 34 
 35         pass
 36 
 37  
 38 
 39     def copy(self, *args, **kwargs): # real signature unknown
 40 
 41         """ Return a shallow copy of a set. 淺拷貝  """
 42 
 43         pass
 44 
 45  
 46 
 47     def difference(self, *args, **kwargs): # real signature unknown
 48 
 49         """
 50 
 51         Return the difference of two or more sets as a new set. A中存在,B中不存在
 52 
 53          
 54 
 55         (i.e. all elements that are in this set but not the others.)
 56 
 57         """
 58 
 59         pass
 60 
 61  
 62 
 63     def difference_update(self, *args, **kwargs): # real signature unknown
 64 
 65         """ Remove all elements of another set from this set.  從當前集合中刪除和B中相同的元素"""
 66 
 67         pass
 68 
 69  
 70 
 71     def discard(self, *args, **kwargs): # real signature unknown
 72 
 73         """
 74 
 75         Remove an element from a set if it is a member.
 76 
 77          
 78 
 79         If the element is not a member, do nothing. 移除指定元素,不存在不保錯
 80 
 81         """
 82 
 83         pass
 84 
 85  
 86 
 87     def intersection(self, *args, **kwargs): # real signature unknown
 88 
 89         """
 90 
 91         Return the intersection of two sets as a new set. 交集
 92 
 93          
 94 
 95         (i.e. all elements that are in both sets.)
 96 
 97         """
 98 
 99         pass
100 
101  
102 
103     def intersection_update(self, *args, **kwargs): # real signature unknown
104 
105         """ Update a set with the intersection of itself and another.  取交集並更更新到A中 """
106 
107         pass
108 
109  
110 
111     def isdisjoint(self, *args, **kwargs): # real signature unknown
112 
113         """ Return True if two sets have a null intersection.  若是沒有交集,返回True,不然返回False"""
114 
115         pass
116 
117  
118 
119     def issubset(self, *args, **kwargs): # real signature unknown
120 
121         """ Report whether another set contains this set.  是不是子序列"""
122 
123         pass
124 
125  
126 
127     def issuperset(self, *args, **kwargs): # real signature unknown
128 
129         """ Report whether this set contains another set. 是不是父序列"""
130 
131         pass
132 
133  
134 
135     def pop(self, *args, **kwargs): # real signature unknown
136 
137         """
138 
139         Remove and return an arbitrary set element.
140 
141         Raises KeyError if the set is empty. 移除元素
142 
143         """
144 
145         pass
146 
147  
148 
149     def remove(self, *args, **kwargs): # real signature unknown
150 
151         """
152 
153         Remove an element from a set; it must be a member.
154 
155          
156 
157         If the element is not a member, raise a KeyError. 移除指定元素,不存在保錯
158 
159         """
160 
161         pass
162 
163  
164 
165     def symmetric_difference(self, *args, **kwargs): # real signature unknown
166 
167         """
168 
169         Return the symmetric difference of two sets as a new set.  對稱交集
170 
171          
172 
173         (i.e. all elements that are in exactly one of the sets.)
174 
175         """
176 
177         pass
178 
179  
180 
181     def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
182 
183         """ Update a set with the symmetric difference of itself and another. 對稱交集,並更新到a中 """
184 
185         pass
186 
187  
188 
189     def union(self, *args, **kwargs): # real signature unknown
190 
191         """
192 
193         Return the union of sets as a new set.  並集
194 
195          
196 
197         (i.e. all elements that are in either set.)
198 
199         """
200 
201         pass
202 
203  
204 
205     def update(self, *args, **kwargs): # real signature unknown
206 
207         """ Update a set with the union of itself and others. 更新 """
208 
209         pass
set

 練習

# 數據庫中原有
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 新彙報的數據
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}

找出須要刪除:
找出須要新建:
找出須要更新:
注意:無需考慮內部元素是否改變,只要原來存在,新彙報也存在,就是須要更新

方法一:

old_key = old_dict.keys() #['#3', '#2', '#1']
new_key = new_dict.keys() #['#3', '#1', '#4']

old_set = set(old_key)
new_set = set(new_key)


inter_set = old_set.intersection(new_set)#查找兩個集合的交集,即須要新建的集合
print(inter_set)
>>>set(['#3', '#1'])

del_set = old_set.difference(inter_set)#比較old_set和inter_set,找到需刪除的元素
print(del_set)
>>>set(['#2']) add_set
= new_set.difference(inter_set)#比較new_set和inter_set,找到須要更新的元素 print(add_set)
>>>set(['#4'])

方法二:

old_key = old_dict.keys() #['#3', '#2', '#1']
new_key = new_dict.keys() #['#3', '#1', '#4']

old_set = set(old_key)
new_set = set(new_key)


del_set = old_set.difference(new_dict)
print(del_set) #[2]

add_set = new_set.difference(old_set)
print(add_set) #[4]

update_set = old_set.intersection(new_set)
print(update_set) #['#3', '#1']

 

三元運算

三元運算(三目運算),是對簡單的條件語句if,else的縮寫。

if 1 == 1:
    name = 'alex'
else:
    name = 'eric'

print(name)
>>>alex

result = 值1 if 條件 else 值2
# 若是條件成立,那麼將 「值1」 賦值給result變量,不然,將「值2」賦值給result變量

name = 'alex' if 1 == 1 else 'eric'
print(name)
>>>alex

 

深淺拷貝

 

字符串,鏈表數據的存儲和修改

字符串  一次性被建立,不能被修改,只要修改字符串,內存將從新建立新新字符串,並把原來的指針指向新的字符串。

鏈表     自動記錄上下原始的位子,若在列表增長元素append(444,555),元素在內存中被建立,鏈表的上一個元素的指針自動指向下一個元素的位置。

 

name_list = ['alex', 'eric', 'tony']
name_list[0] = ("abex")
print(name_list)
>>>

['abex', 'eric', 'tony']


name_list.append("seven")
print(name_list)

>>>['abex', 'eric', 'tony', 'seven']

數字和字符串

  對於 數字 和 字符串 而言,賦值、淺拷貝和深拷貝無心義,由於其永遠指向同一個內存地址。

  因爲字符串和數值都在數據的底層,對他們進行拷貝,賦值,他們的指向地址都相同的。

>>> import copy
>>> n1 = 123
>>> n2 = n1
>>> print(id(n1))
494886544
>>> print(id(n2))
494886544
>>> 
>>> import copy
>>> n1 = 123
>>> n2 = copy.copy(n1)
>>> n3 = copy.deepcopy(n1)

>>> print(id(n1))
494886544
>>> print(id(n2))
494886544
>>> print(id(n3))
494886544
>>> 

 

其餘基本數據類型

對於字典、元祖、列表 而言,進行賦值、淺拷貝和深拷貝時,變量的索引部分將從新創建在內存中,索引指向的底層數字和字符串與原來的內存地址相同。

    

一、賦值

賦值,只是建立一個變量,該變量指向原來內存地址,如:

n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]}

n2 = n1

 

二、淺拷貝

淺拷貝,在內存中只額外建立第一層數據

import copy

n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]}
 
n3 = copy.copy(n1)

 

三、深拷貝

深拷貝,在內存中將全部的數據從新建立一份(排除最後一層,即:python內部對字符串和數字的優化)

import copy

n1 = {"k1": "wu", "k2": 123, "k3": ["alex", 456]} 

n4 = copy.deepcopy(n1)

 

函數

  • 函數式:將某功能代碼封裝到函數中,往後便無需重複編寫,僅調用函數便可
  • 面向對象:對函數進行分類和封裝,讓開發「更快更好更強...」

 

函數定義和使用

def 函數名(參數):

   ... 函數體

   ... 返回值

函數名()#調用函數

ret =函數名()#輸出返回值
print('ret')

def foo(): #definition/declaration
      print('bar')
     
foo   #function object/reference
foo() #function call/invocation            

 

返回值

因爲實際的函數更接近過程,執行過程當中不顯示返回任何東西,對「什麼都不返回的函數」python設定了特殊的名字「None」

「return」能夠設定返回str,int,list,tuple,dict,set......

#執行過程沒有返回值,若是用「res」保存返回值,該值爲「None」
def
email(): print("send mail") ret = email() #執行函數 print(ret) #輸出函數返回值 >>> send mail None
#設定返回函數「return」
def
email(): print("send mail") return 'Ok'#設定返回函數的返回值 ret = email() print(ret) >>> send mail Ok
def email():

    if True:
        return True
    else:
        return False

ret = email()
if ret:#函數return返回什麼值,ret返回什麼值
    print("Ok")
else:
    print("No")

>>>
Ok

 

函數的普通參數

  形式參數:形式參數是函數定義中的,系統沒有爲其分配內存空間,可是在定義裏面可使用的參數。

  實際參數:實際參數是函數調用的時候傳給函數的變量

  形式參數,實際參數(按照形式參數默認順序傳遞)

def func1(x,y):#(x, y)形式參數
    print(x,y)

def func2(x,y):#(x, y)形式參數
    print(x+y)

func1(10, 20)#(10,20)實際參數
func2(10, 100)#(10,100)實際參數

>>>
(10, 20)
110
def func(arg):#形式參數 if arg.isdigit(): #判斷條件 return True #返回值 else:
        return False #返回值

k1 = func('123')#實際參數 if k1: #根據返回值判斷 print('Ok')
else:
    print('No')

>>>
Ok
def func(args): #函數的傳值, arg引用li的列表,不會從新建立新的[11,22]
    args.append(123)

li = [11,22,]
func(li)
print(li)
def f1(args): #fi(li)把列表 li 傳到args中,args指向 li列表 的數值
    args = 123 # args = 123,args的指向改成 ‘123’,不在指向 li 列表

li = [11, 22, 33]
f1(li)
print(li)

>>>
[11, 22, 33]

 

形式參數和實際參數練習

 1 def email(email_address, content, subject):
 2 
 3     import smtplib
 4     from email.mime.text import MIMEText
 5     from email.utils import formataddr
 6 
 7     ret= True
 8 
 9     Try:
10     
11         msg = MIMEText(content, 'plain', 'utf-8')
12         msg['From'] = formataddr(["銀角大王",'wptawy@126.com'])
13         msg['To'] = formataddr(["蟻民",address])
14         msg['Subject'] = subject
15   
16         server = smtplib.SMTP("smtp.126.com", 25)
17         server.login("wptawy@126.com", "郵箱密碼")
18         server.sendmail('wptawy@126.com', [address,], msg.as_string())
19         server.quit()    
20 
21     except:
22     
23         ret = False
24 
25     return ret
26 
27 res = email('123456@qq.com', 'No Content', 'No Subject')
28 
29 if res:
30     print('發送成功')
31 else:
32     print('發送失敗')

     指定參數(能夠不按照默認形參和實參的順序,指定參數)

def func(arg1, arg2):

    if arg1.isdigit() and arg2.isspace():
        return True
    else:
        return False

k1 = func(arg2='  ', arg1='123')#指定參數
# k1 = func('abc')

if k1:
    print('Ok')
else:
    print('No')

>>>
Ok

   函數的默認值

  下形式參數中,指定參數的值。

  形式參數的默認值應放在形參的最後。

def func(arg1, arg2='100'):#arg2的默認值爲100 print(arg1+arg2)

func(arg1='alex')#只傳arg1的實參值 >>>
alex100

def func(arg1, arg2='100'):

    print(arg1+arg2)

func(arg1='alex', arg2='seven')#arg2的實參爲‘seven’ >>>
alexseven

   動態參數

   (1) 形式參數前加上'*'(*arg),將會把每一個實參做爲 元組 的元素傳到函數中

def func(*a): #動態參數
    print(type(a))

func(123)

>>>
<type 'tuple'>#生成元組
def func(*a):#動態參數 print(a,(type(a)))

func(123, 456, 789)#加入多個實參 >>>
((123, 456, 789), <type 'tuple'>)

  (2) 形式參數前加上'**'(*kwarg),需將實參以key, value的形式傳到函數中,拼接成 字典

def func(**a):
    print(a,(type(a)))

func(k1 = 123, k2 = 456)

>>>
({'k2': 456, 'k1': 123}, <type 'dict'>)

   (3) 兩種動態參數結合,

    形參的順序:arg > *arg>**kwarg

def func(p,*a,**aa):
    print(a,(type(a)))
    print(aa, (type(aa)))

func(11,22,33, k1 = 123, k2 = 456)

>>>
(11, <type 'int'>)
((22, 33), <type 'tuple'>)
({'k2': 456, 'k1': 123}, <type 'dict'>)

    (4) 實際參數加'*',傳入的參數將做爲元組的惟一元素

    *args ---> *list

def func(*args):
    print(args, (type(args)))

li = [11,22,33]
func(li)
func(*li)#實參加'*'做爲元組惟一元素 >>>
(([11, 22, 33],), <type 'tuple'>)
((11, 22, 33), <type 'tuple'>)

    (5) 實際參數加「**」,傳入的參數將做爲字典的鍵值對

    **kwargs ---> **dict

def func(**kwargs):
    print(kwargs, (type(kwargs)))

dic = {"k1":123, "k2":456}
func(k1=dic)
func(**dic)

>>>
({'k1': {'k2': 456, 'k1': 123}}, <type 'dict'>)
({'k2': 456, 'k1': 123}, <type 'dict'>)

     (6) 以函數做爲參數代入另一個函數中

def f1():#f1 = 函數
    print("F1")
#f1代指函數
#f1()執行函數

def f2(arg):
    arg() #執行arg函數,至關於執行F1() return "F2"

#執行f2函數,把f1函數當作參數
ret = f2(f1)
print(ret)

>>>
F1
F2

     函數內部操做流程

 

全局變量和局部變量

  在函數外部設定全局變量,函數內部的局部變量不影響全局變量的賦值

p = 'alex'#全局變量

def func1():#局部變量
    a = 123
    p = 'eric'#沒有改變全局變量
    print(a)

def func2():    
    a = 456# 局部變量
    print(p) 
    print(a)

func1()
func2()

>>>
123
alex
456

  假如須要在函數改變全局變量,須要聲明「global 變量名」

p = 'alex'#全局變量

def func1():#局部變量
    a = 123
    global p  #global聲明全局變量
    p = 'eric' #全局變量的從新賦值
    print(a)

def func2():
    a = 456# 局部變量
    print(p)
    print(a)

func1()
func2()

>>>
123
eric
456

 

匿名函數lambda表達式

lambda [arg1[, arg2, ... argN]] : expression

對於簡單的函數,也存在一種簡便的表示方式,即:lambda表達式

def add(x, y): return x + y <===> lambda x, y: x+y
def add(x, y):

    return x + y

ret = add(10, 20)
print(ret)

>>> 
30

func = lambda x, y: x+y

res = func(x=10, y=20)
print(res)

>>>
30

 內置函數

abs()

返回輸入數字的絕對值。Return the absolute value of a number. 

f1 = abs(-123)
print(f1)
>>>
123

all()

循環參數,若每一個元素都爲真,返回True,不然返回False。Return True if all elements of the iterable are true (or if the iterable is empty).

r = all([True, True, False])
print(r)

>>>
False

any()

循環參數,若每一個元素都爲假,返回True,其中有一個元素爲真返回False。Return True if any element of the iterable is true. If the iterable is empty, return False.

r = any([0, None, False, " ", [ ], ( ), { }])
print(r)

>>>
True

ascii()

在ascii()對象的類中找到__repr__,得到其返回值。As repr(), return a string containing a printable representation of an object, but escape the non-ASCII characters in the string returned by repr() using\x\u or \U escapes. 

class Foo():
    def __repr__(self):
        return("Hello")

obj = Foo()

r = ascii(obj) #ascii在obj對應的類中,找出__repr__的返回值
print(r)

>>>
Hello

bin() 二進制

r = bin(11) #轉換爲二進制0,1
print(r)

>>>
0b1011

oct() 八進制

s = oct(7) #轉換爲八進制
print(s)

>>>
0o7

t = oct(8)
print(8)

>>>
0o10

int() 十進制

r = int(0xf)
print(r)

>>>
15
i = int('ob11', base= 2)
print(i)

>>>
3

j = int('11', base=8)
print(j)

>>>
9

k = int('0xe', base=16)
print(k)

>>>
14

hex() 十六進制

分別用數字1-9,字母a-g表明數字

s = hex(9)
print(s)

>>>
0x9

t = hex(10)
print(t)

>>>
0xa

r = hex(15)
print(r)

>>>
0xf

 ord()

輸入一個字符,返回該字符的萬國碼號。Given a string representing one Unicode character, return an integer representing the Unicode code point of that character.

a = ord("t")
print(a)

>>>
116

chr()

輸入一個萬國碼,返回萬國碼相對的字符。Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.

a = chr(65)
print(a)

>>>
A
#chr()的函數應用

import random 

temp = ''
for i in range(6):
    num = random.randrange(0, 4)#生成0-4的隨機數 if num == 2 or num ==4: #隨機數等於2或4時候
        rad2 = random.randrange(0, 10)#生成0-10的隨機數字
        temp = temp + str(rad2)#生成的隨機數字轉爲字符串 else:
        rad1 = random.randrange(65,91)#生成65-91的隨機數
        c1 = chr(rad1)#chr()函數返回字母
        temp = temp +c1

print(temp)

 callable()

判斷輸入的對象是否爲函數,函數返回True,非函數返回False。Return True if the object argument appears callable, False if not.

def f1():
    return "123"

r = callable(f1)
print(r)

>>>
True

complex()

返回複數形式的數字

r = complex(123+2j)
print(r)

>>>
(123+2j)

 dir()

查看類中可執行的函數

a = tuple()
print(dir(a))

>>>
['__add__', '__class__',...]

divmod()

輸出除法計算的結果,商和餘數。Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. 

a = 10/3
print(a)

>>>
3.3333333333333335

r = divmod(10, 3)
print(r)

>>>
(3, 1)

eval()

執行一個字符串形式的表達式,返回表達式的結果。This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs).

ret = eval('a + 100', {'a': 99})
print(ret)

>>>
199

exec()

執行字符串的中python代碼,直接返回結果。This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs).

exec("for i in range(3):print(i)")

>>>
0
1
2

complie()編譯代碼

eval() 執行表達式,生成返回值

exec() 執行python代碼,返回結果

 

filter()

按照過濾條件函數,過濾一組可迭代的數組。Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator

def func(a):
    if a > 22:
        return True
    else:
        return False

ret = filter(func, [11, 22, 33, 44, ])

for i in ret:
    print(i)

>>>
33
44
ret = filter(lambda a: a > 22, [11, 22, 33, 44, ])

for i in ret:
    print(i)

>>>
33
44
def MyFilter(func, seq):
    result = []
    for i in seq:
        #func = f1
        #func(x)執行f1的函數,並得到返回值,將其賦值給ret
        ret = func(i)
        if ret:
            result.append(i)
    return result

def f1(x):
    if x > 22:
        return True
    else:
        return False

r = MyFilter(f1, [11, 22, 33, 44, 55, 66])
print(r)

map()

將函數做用在序列的每一個元素上,而後建立有每次函數函數應用的主城的返回值列表。Return an iterator that applies function to every item of iterable, yielding the results.

def f1(x):
    return x + 100
ret = map(f1, [1, 2, 3, 4, 5])
for i in ret:
    print(i)

>>>
101
102
103
104
105
li = [1, 2, 3, 4, 5]
ret = map(lambda x: x+100 if x % 2 == 1 else x, li)
for i in ret:
    print(i)

>>>
101
2
103
4
105
li = [11, 22, 33, 44, 55, 66]
def x(arg):
    return arg+100

def MyMap(func, arg):
    result = []
    for i in arg:
        ret = func(i) #fun(11) x(11)
        result.append(ret)
    return result

r = MyMap(x, li)

globals()

獲取全局變量。Return a dictionary representing the current global symbol table. 

local()

獲取局部變量。Update and return a dictionary representing the current local symbol table.

first_name = 'samsam'
def func():
    last_name = 'broadview'
    print(locals())

func()
print(globals())

>>>
{'last_name': 'broadview'}
{'__name__': '__main__', '__file__': , 'first_name': 'samsam', ...}

hash()

將函數的字符串或數字轉換爲哈希值。Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. 

dic = {
    "qwertyuiop123456789:123"
}
i = hash("qwertyuiop123456789:123")
print(i)

>>>
831660209

isinstance()

檢驗輸入的對象和類是相同的類屬性。Return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. 

dic = {"k1":"v1"}
i = isinstance(dic, dict)
print(i)

>>>
True

iter()

建立一個能夠被迭代的對象。Return an iterator object.

next()

在能夠被迭代的對象按順序取一個值。Retrieve the next item from the iterator by calling its __next__() method.

obj = iter([11,22,33,44])

print(obj)
r1 = next(obj)
print(r1)
r1 = next(obj)
print(r1)
r1 = next(obj)
print(r1)
r1 = next(obj)
print(r1)

>>>
11
22
33
44

pow()

冪運算。Return x to the power y.

i = pow(2, 10)
print(i)

>>>
1024

round()

四捨五入。Return the floating point value number rounded to ndigits digits after the decimal point.

i = round(3.6)
print(i)

>>>
4

zip()

將多個可迭代的對象按照想用的序號合併,生成新的迭代對象。Make an iterator that aggregates elements from each of the iterables.

li1 = [11,22,33,44]
li2 = ["a","b","c","d"]

r = zip(li1, li2)
for i in r:
    print(i)

>>>
(11, 'a')
(22, 'b')
(33, 'c')
(44, 'd')

 排序

sort() 按照從小到大的順序排列,返回原來的對象

sorted() 按照從小到大的順序排列,返回生成新的對象

li = [1,211,22,3,4]
li.sort()
print(li)
>>>
[1, 3, 4, 22, 211]

li = [1,211,22,3,4]
new_li = sorted(li)
print(new_li)
>>>
[1, 3, 4, 22, 211]
char = ["1", "2", "3", "4", "5", "a", "AB", "bc", "_","def延", "", "", "", "", "", "", "", "", "", "", "", ""]
new_char = sorted(char)
print(new_char)
for i in new_char:
    print(bytes(i, encoding="utf-8"))

>>>
['1', '2', '3', '4', '5', 'AB', '_', 'a', 'bc', 'def延', '', '', '', '', '', '', '', '', '', '', '', '']
b'1'
b'2'
b'3'
b'4'
b'5'
b'AB'
b'_'
b'a'
b'bc'
b'def\xe5\xbb\xb6'
b'\xe5\x88\x81'
b'\xe5\x9d\xb7'
b'\xe6\x83\x95'
b'\xe6\x9b\xb3'
b'\xe6\x9c\x8b'
b'\xe6\xbe\x84'
b'\xe7\xbe\x9a'
b'\xe8\x83\x9a'
b'\xe8\x90\x8d'
b'\xe8\x90\xbd'
b'\xe8\x97\xbb'
b'\xe8\xb0\xb7'

 open()

用於文件處理

操做文件時,通常須要經歷以下步驟:

  • 打開文件
  • 操做文件
  • 關閉文件

 

基本操做文件方式

open(文件名/路徑,模式,編碼),默認模式爲「只讀」

f = open('test.log', "r")
data = f.read()
f.close()
print(data)

>>>
testlog

打開文件時,須要指定文件路徑和以何等方式打開文件,打開後,便可獲取該文件句柄,往後經過此文件句柄對該文件操做。

打開文件的模式: 

  • r ,只讀模式【默認】
  • f = open('test.log')
    data = f.read()
    f.close()
     print(data)
    
    >>>
    abc123

     

  • w,只寫模式【不可讀;文件不存在則建立;文件存在則清空內容;】
  • f = open('test.log', 'w')
    data = f.write('defg123456') #以寫方式覆蓋文件
    f.close()
    print(data)
    
    >>>
    10  #寫入10個字符
    f = open('test.log', 'w')
    data = f.read()
    f.close()
    print(data)
    
    >>>
        data = f.read()
    io.UnsupportedOperation: not readable#只寫方式不能讀取文件內同

     

  • x, 只寫模式【不可讀;文件不存在則建立;文件存在則報錯】
  • f = open('test2.log', 'x')#文件不存在,建立一個新的文件
    f.write("qwe456") 
    f.close()
    
    f = open('test2.log', 'x')
    f.write("zxcv123456") 
    f.close()
    
    >>>
        f = open('test2.log', 'x')
    FileExistsError: [Errno 17] File exists: 'test2.log'#文件已經存在,不能建立同名文件

     

  • a, 追加模式【不可讀;文件不存在則建立;文件存在則只追加內容;】
  • f = open('test2.log', 'a')
    data = f.write("9876543210")
    f.close()
    print(data)
    
    >>>
    10 #寫入10個字符

     

"+" 表示能夠同時讀寫某個文件

  • r+, 讀寫【可讀,可寫】

    先讀取文檔,在文檔末尾追加寫入,指針移到最後

f = open("test.log", 'r+', encoding = "utf-8")
print(f.tell()) #顯示指針位置,指針從開始向後讀取
f.write("123456")

data = f.read()

print(data)
print(f.tell()) #讀取文件後指針位置

f.close()

>>>
0
123456
6
  • w+,寫讀【可讀,可寫】

    先把文件內容清空,從開始向後讀取文件;從新寫入內容後,指針移到最後,讀取文件。

    

f = open("test.log", 'w+', encoding = "utf-8")
f.write("123456")#寫入完成後,文檔指針位置在文件末尾
f.seek(0)#設定指針在文檔開始
data = f.read()
print(data)

 

  • x+ ,寫讀【可讀,可寫】

    若文件存在,系統報錯,建新文件,再寫入內容後,指針移到最後,讀取文件。

  • a+, 寫讀【可讀,可寫】

    文件打開同時,文檔指針已經設定在最後, 寫入文件後,指針留在文件的最後。

    

f = open("test.log", 'a+', encodig"utf-8")
f.write("987654")
print(f.tell()) #顯示指針位置 f.seek(0)    #設定指針爲文檔最開始 data
= f.read() print(data)

>>>
6
987654


r+ w+ x+ a+都以指針位置讀取或寫入數據。

 

 "b"表示以字節(bytes)的方式操做

  • rb  或 r+b
  • f = open('test2.log', 'wb')
    f.write(bytes("中國", encoding='utf-8'))
    f.close()
    
    
    f = open('test2.log', "rb")
    data = f.read()
    f.close()
    print(data)
    str_data = str(data, encoding='utf - 8')
    print(str_data)
    
    >>>
    b'\xe4\xb8\xad\xe5\x9b\xbd'
    中國

     

  • wb 或 w+b
  • f = open('test2.log', 'wb')
    str_data = "中國" bytes_data = bytes(str_data, encoding = 'utf-8')
    #指定寫如的編碼
    f.write(bytes_data) f.close()
    f = open('test2.log', 'wb')
    f.write("中國")
    f.close()
    
    >>>
        f.write("中國")
    TypeError: a bytes-like object is required, not 'str'
  • xb 或 x+b
  • ab 或 a+b

 注:以b方式打開時,讀取到的內容是字節類型,寫入時也須要提供字節類型

 

普通打開方式

python內部將底層010101010的字節 轉換成 字符串

 

二進制打開方式

python將讀取將底層010101010的字節 再按照程序員設定的編碼,轉換成字符串。

f = open('test2.log', 'wb')
f.write(bytes("中國", encoding='utf-8'))
f.close()

f = open('test2.log', "rb")
data = f.read()
f.close()
print(data)
str_data = str(data, encoding='utf - 8')
print(str_data)

>>>
b'\xe4\xb8\xad\xe5\x9b\xbd'
中國
相關文章
相關標籤/搜索