目錄:html
1.集合setnode
2.計數器python
3.有序字典編程
4.默認字典服務器
5.可命名元組app
6.隊列ide
7.深淺拷貝函數式編程
8.函數函數
9.lambda表達式oop
10.內置函數
1、集合set
set是一個無序且不重複的元素集合
1 class set(object): 2 """ 3 set() -> new empty set object 4 set(iterable) -> new set object 5 6 Build an unordered collection of unique elements. 7 """ 8 def add(self, *args, **kwargs): # real signature unknown 9 """ 添加 """ 10 """ 11 Add an element to a set. 12 13 This has no effect if the element is already present. 14 """ 15 pass 16 17 def clear(self, *args, **kwargs): # real signature unknown 18 """ Remove all elements from this set. """ 19 pass 20 21 def copy(self, *args, **kwargs): # real signature unknown 22 """ Return a shallow copy of a set. """ 23 pass 24 25 def difference(self, *args, **kwargs): # real signature unknown 26 """ 27 Return the difference of two or more sets as a new set. 28 29 (i.e. all elements that are in this set but not the others.) 30 """ 31 pass 32 33 def difference_update(self, *args, **kwargs): # real signature unknown 34 """ 刪除當前set中的全部包含在 new set 裏的元素 """ 35 """ Remove all elements of another set from this set. """ 36 pass 37 38 def discard(self, *args, **kwargs): # real signature unknown 39 """ 移除元素 """ 40 """ 41 Remove an element from a set if it is a member. 42 43 If the element is not a member, do nothing. 44 """ 45 pass 46 47 def intersection(self, *args, **kwargs): # real signature unknown 48 """ 取交集,新建立一個set """ 49 """ 50 Return the intersection of two or more sets as a new set. 51 52 (i.e. elements that are common to all of the sets.) 53 """ 54 pass 55 56 def intersection_update(self, *args, **kwargs): # real signature unknown 57 """ 取交集,修改原來set """ 58 """ Update a set with the intersection of itself and another. """ 59 pass 60 61 def isdisjoint(self, *args, **kwargs): # real signature unknown 62 """ 若是沒有交集,返回true """ 63 """ Return True if two sets have a null intersection. """ 64 pass 65 66 def issubset(self, *args, **kwargs): # real signature unknown 67 """ 是不是子集 """ 68 """ Report whether another set contains this set. """ 69 pass 70 71 def issuperset(self, *args, **kwargs): # real signature unknown 72 """ 是不是父集 """ 73 """ Report whether this set contains another set. """ 74 pass 75 76 def pop(self, *args, **kwargs): # real signature unknown 77 """ 移除 """ 78 """ 79 Remove and return an arbitrary set element. 80 Raises KeyError if the set is empty. 81 """ 82 pass 83 84 def remove(self, *args, **kwargs): # real signature unknown 85 """ 移除 """ 86 """ 87 Remove an element from a set; it must be a member. 88 89 If the element is not a member, raise a KeyError. 90 """ 91 pass 92 93 def symmetric_difference(self, *args, **kwargs): # real signature unknown 94 """ 差集,建立新對象""" 95 """ 96 Return the symmetric difference of two sets as a new set. 97 98 (i.e. all elements that are in exactly one of the sets.) 99 """ 100 pass 101 102 def symmetric_difference_update(self, *args, **kwargs): # real signature unknown 103 """ 差集,改變原來 """ 104 """ Update a set with the symmetric difference of itself and another. """ 105 pass 106 107 def union(self, *args, **kwargs): # real signature unknown 108 """ 並集 """ 109 """ 110 Return the union of sets as a new set. 111 112 (i.e. all elements that are in either set.) 113 """ 114 pass 115 116 def update(self, *args, **kwargs): # real signature unknown 117 """ 更新 """ 118 """ Update a set with the union of itself and others. """ 119 pass 120 121 def __and__(self, y): # real signature unknown; restored from __doc__ 122 """ x.__and__(y) <==> x&y """ 123 pass 124 125 def __cmp__(self, y): # real signature unknown; restored from __doc__ 126 """ x.__cmp__(y) <==> cmp(x,y) """ 127 pass 128 129 def __contains__(self, y): # real signature unknown; restored from __doc__ 130 """ x.__contains__(y) <==> y in x. """ 131 pass 132 133 def __eq__(self, y): # real signature unknown; restored from __doc__ 134 """ x.__eq__(y) <==> x==y """ 135 pass 136 137 def __getattribute__(self, name): # real signature unknown; restored from __doc__ 138 """ x.__getattribute__('name') <==> x.name """ 139 pass 140 141 def __ge__(self, y): # real signature unknown; restored from __doc__ 142 """ x.__ge__(y) <==> x>=y """ 143 pass 144 145 def __gt__(self, y): # real signature unknown; restored from __doc__ 146 """ x.__gt__(y) <==> x>y """ 147 pass 148 149 def __iand__(self, y): # real signature unknown; restored from __doc__ 150 """ x.__iand__(y) <==> x&=y """ 151 pass 152 153 def __init__(self, seq=()): # known special case of set.__init__ 154 """ 155 set() -> new empty set object 156 set(iterable) -> new set object 157 158 Build an unordered collection of unique elements. 159 # (copied from class doc) 160 """ 161 pass 162 163 def __ior__(self, y): # real signature unknown; restored from __doc__ 164 """ x.__ior__(y) <==> x|=y """ 165 pass 166 167 def __isub__(self, y): # real signature unknown; restored from __doc__ 168 """ x.__isub__(y) <==> x-=y """ 169 pass 170 171 def __iter__(self): # real signature unknown; restored from __doc__ 172 """ x.__iter__() <==> iter(x) """ 173 pass 174 175 def __ixor__(self, y): # real signature unknown; restored from __doc__ 176 """ x.__ixor__(y) <==> x^=y """ 177 pass 178 179 def __len__(self): # real signature unknown; restored from __doc__ 180 """ x.__len__() <==> len(x) """ 181 pass 182 183 def __le__(self, y): # real signature unknown; restored from __doc__ 184 """ x.__le__(y) <==> x<=y """ 185 pass 186 187 def __lt__(self, y): # real signature unknown; restored from __doc__ 188 """ x.__lt__(y) <==> x<y """ 189 pass 190 191 @staticmethod # known case of __new__ 192 def __new__(S, *more): # real signature unknown; restored from __doc__ 193 """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ 194 pass 195 196 def __ne__(self, y): # real signature unknown; restored from __doc__ 197 """ x.__ne__(y) <==> x!=y """ 198 pass 199 200 def __or__(self, y): # real signature unknown; restored from __doc__ 201 """ x.__or__(y) <==> x|y """ 202 pass 203 204 def __rand__(self, y): # real signature unknown; restored from __doc__ 205 """ x.__rand__(y) <==> y&x """ 206 pass 207 208 def __reduce__(self, *args, **kwargs): # real signature unknown 209 """ Return state information for pickling. """ 210 pass 211 212 def __repr__(self): # real signature unknown; restored from __doc__ 213 """ x.__repr__() <==> repr(x) """ 214 pass 215 216 def __ror__(self, y): # real signature unknown; restored from __doc__ 217 """ x.__ror__(y) <==> y|x """ 218 pass 219 220 def __rsub__(self, y): # real signature unknown; restored from __doc__ 221 """ x.__rsub__(y) <==> y-x """ 222 pass 223 224 def __rxor__(self, y): # real signature unknown; restored from __doc__ 225 """ x.__rxor__(y) <==> y^x """ 226 pass 227 228 def __sizeof__(self): # real signature unknown; restored from __doc__ 229 """ S.__sizeof__() -> size of S in memory, in bytes """ 230 pass 231 232 def __sub__(self, y): # real signature unknown; restored from __doc__ 233 """ x.__sub__(y) <==> x-y """ 234 pass 235 236 def __xor__(self, y): # real signature unknown; restored from __doc__ 237 """ x.__xor__(y) <==> x^y """ 238 pass 239 240 __hash__ = None 241 242 set
2、計數器(counter)
Counter是對字典類型的補充,用於追蹤值出現的次數
ps:具有字典的全部功能+本身的功能
c = Counter('abcdeabcdabcaba') print c 輸出:Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
1 ######################################################################## 2 ### Counter 3 ######################################################################## 4 5 class Counter(dict): 6 '''Dict subclass for counting hashable items. Sometimes called a bag 7 or multiset. Elements are stored as dictionary keys and their counts 8 are stored as dictionary values. 9 10 >>> c = Counter('abcdeabcdabcaba') # count elements from a string 11 12 >>> c.most_common(3) # three most common elements 13 [('a', 5), ('b', 4), ('c', 3)] 14 >>> sorted(c) # list all unique elements 15 ['a', 'b', 'c', 'd', 'e'] 16 >>> ''.join(sorted(c.elements())) # list elements with repetitions 17 'aaaaabbbbcccdde' 18 >>> sum(c.values()) # total of all counts 19 20 >>> c['a'] # count of letter 'a' 21 >>> for elem in 'shazam': # update counts from an iterable 22 ... c[elem] += 1 # by adding 1 to each element's count 23 >>> c['a'] # now there are seven 'a' 24 >>> del c['b'] # remove all 'b' 25 >>> c['b'] # now there are zero 'b' 26 27 >>> d = Counter('simsalabim') # make another counter 28 >>> c.update(d) # add in the second counter 29 >>> c['a'] # now there are nine 'a' 30 31 >>> c.clear() # empty the counter 32 >>> c 33 Counter() 34 35 Note: If a count is set to zero or reduced to zero, it will remain 36 in the counter until the entry is deleted or the counter is cleared: 37 38 >>> c = Counter('aaabbc') 39 >>> c['b'] -= 2 # reduce the count of 'b' by two 40 >>> c.most_common() # 'b' is still in, but its count is zero 41 [('a', 3), ('c', 1), ('b', 0)] 42 43 ''' 44 # References: 45 # http://en.wikipedia.org/wiki/Multiset 46 # http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html 47 # http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm 48 # http://code.activestate.com/recipes/259174/ 49 # Knuth, TAOCP Vol. II section 4.6.3 50 51 def __init__(self, iterable=None, **kwds): 52 '''Create a new, empty Counter object. And if given, count elements 53 from an input iterable. Or, initialize the count from another mapping 54 of elements to their counts. 55 56 >>> c = Counter() # a new, empty counter 57 >>> c = Counter('gallahad') # a new counter from an iterable 58 >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping 59 >>> c = Counter(a=4, b=2) # a new counter from keyword args 60 61 ''' 62 super(Counter, self).__init__() 63 self.update(iterable, **kwds) 64 65 def __missing__(self, key): 66 """ 對於不存在的元素,返回計數器爲0 """ 67 'The count of elements not in the Counter is zero.' 68 # Needed so that self[missing_item] does not raise KeyError 69 return 0 70 71 def most_common(self, n=None): 72 """ 數量大於等n的全部元素和計數器 """ 73 '''List the n most common elements and their counts from the most 74 common to the least. If n is None, then list all element counts. 75 76 >>> Counter('abcdeabcdabcaba').most_common(3) 77 [('a', 5), ('b', 4), ('c', 3)] 78 79 ''' 80 # Emulate Bag.sortedByCount from Smalltalk 81 if n is None: 82 return sorted(self.iteritems(), key=_itemgetter(1), reverse=True) 83 return _heapq.nlargest(n, self.iteritems(), key=_itemgetter(1)) 84 85 def elements(self): 86 """ 計數器中的全部元素,注:此處非全部元素集合,而是包含全部元素集合的迭代器 """ 87 '''Iterator over elements repeating each as many times as its count. 88 89 >>> c = Counter('ABCABC') 90 >>> sorted(c.elements()) 91 ['A', 'A', 'B', 'B', 'C', 'C'] 92 93 # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1 94 >>> prime_factors = Counter({2: 2, 3: 3, 17: 1}) 95 >>> product = 1 96 >>> for factor in prime_factors.elements(): # loop over factors 97 ... product *= factor # and multiply them 98 >>> product 99 100 Note, if an element's count has been set to zero or is a negative 101 number, elements() will ignore it. 102 103 ''' 104 # Emulate Bag.do from Smalltalk and Multiset.begin from C++. 105 return _chain.from_iterable(_starmap(_repeat, self.iteritems())) 106 107 # Override dict methods where necessary 108 109 @classmethod 110 def fromkeys(cls, iterable, v=None): 111 # There is no equivalent method for counters because setting v=1 112 # means that no element can have a count greater than one. 113 raise NotImplementedError( 114 'Counter.fromkeys() is undefined. Use Counter(iterable) instead.') 115 116 def update(self, iterable=None, **kwds): 117 """ 更新計數器,其實就是增長;若是原來沒有,則新建,若是有則加一 """ 118 '''Like dict.update() but add counts instead of replacing them. 119 120 Source can be an iterable, a dictionary, or another Counter instance. 121 122 >>> c = Counter('which') 123 >>> c.update('witch') # add elements from another iterable 124 >>> d = Counter('watch') 125 >>> c.update(d) # add elements from another counter 126 >>> c['h'] # four 'h' in which, witch, and watch 127 128 ''' 129 # The regular dict.update() operation makes no sense here because the 130 # replace behavior results in the some of original untouched counts 131 # being mixed-in with all of the other counts for a mismash that 132 # doesn't have a straight-forward interpretation in most counting 133 # contexts. Instead, we implement straight-addition. Both the inputs 134 # and outputs are allowed to contain zero and negative counts. 135 136 if iterable is not None: 137 if isinstance(iterable, Mapping): 138 if self: 139 self_get = self.get 140 for elem, count in iterable.iteritems(): 141 self[elem] = self_get(elem, 0) + count 142 else: 143 super(Counter, self).update(iterable) # fast path when counter is empty 144 else: 145 self_get = self.get 146 for elem in iterable: 147 self[elem] = self_get(elem, 0) + 1 148 if kwds: 149 self.update(kwds) 150 151 def subtract(self, iterable=None, **kwds): 152 """ 相減,原來的計數器中的每個元素的數量減去後添加的元素的數量 """ 153 '''Like dict.update() but subtracts counts instead of replacing them. 154 Counts can be reduced below zero. Both the inputs and outputs are 155 allowed to contain zero and negative counts. 156 157 Source can be an iterable, a dictionary, or another Counter instance. 158 159 >>> c = Counter('which') 160 >>> c.subtract('witch') # subtract elements from another iterable 161 >>> c.subtract(Counter('watch')) # subtract elements from another counter 162 >>> c['h'] # 2 in which, minus 1 in witch, minus 1 in watch 163 >>> c['w'] # 1 in which, minus 1 in witch, minus 1 in watch 164 -1 165 166 ''' 167 if iterable is not None: 168 self_get = self.get 169 if isinstance(iterable, Mapping): 170 for elem, count in iterable.items(): 171 self[elem] = self_get(elem, 0) - count 172 else: 173 for elem in iterable: 174 self[elem] = self_get(elem, 0) - 1 175 if kwds: 176 self.subtract(kwds) 177 178 def copy(self): 179 """ 拷貝 """ 180 'Return a shallow copy.' 181 return self.__class__(self) 182 183 def __reduce__(self): 184 """ 返回一個元組(類型,元組) """ 185 return self.__class__, (dict(self),) 186 187 def __delitem__(self, elem): 188 """ 刪除元素 """ 189 'Like dict.__delitem__() but does not raise KeyError for missing values.' 190 if elem in self: 191 super(Counter, self).__delitem__(elem) 192 193 def __repr__(self): 194 if not self: 195 return '%s()' % self.__class__.__name__ 196 items = ', '.join(map('%r: %r'.__mod__, self.most_common())) 197 return '%s({%s})' % (self.__class__.__name__, items) 198 199 # Multiset-style mathematical operations discussed in: 200 # Knuth TAOCP Volume II section 4.6.3 exercise 19 201 # and at http://en.wikipedia.org/wiki/Multiset 202 # 203 # Outputs guaranteed to only include positive counts. 204 # 205 # To strip negative and zero counts, add-in an empty counter: 206 # c += Counter() 207 208 def __add__(self, other): 209 '''Add counts from two counters. 210 211 >>> Counter('abbb') + Counter('bcc') 212 Counter({'b': 4, 'c': 2, 'a': 1}) 213 214 ''' 215 if not isinstance(other, Counter): 216 return NotImplemented 217 result = Counter() 218 for elem, count in self.items(): 219 newcount = count + other[elem] 220 if newcount > 0: 221 result[elem] = newcount 222 for elem, count in other.items(): 223 if elem not in self and count > 0: 224 result[elem] = count 225 return result 226 227 def __sub__(self, other): 228 ''' Subtract count, but keep only results with positive counts. 229 230 >>> Counter('abbbc') - Counter('bccd') 231 Counter({'b': 2, 'a': 1}) 232 233 ''' 234 if not isinstance(other, Counter): 235 return NotImplemented 236 result = Counter() 237 for elem, count in self.items(): 238 newcount = count - other[elem] 239 if newcount > 0: 240 result[elem] = newcount 241 for elem, count in other.items(): 242 if elem not in self and count < 0: 243 result[elem] = 0 - count 244 return result 245 246 def __or__(self, other): 247 '''Union is the maximum of value in either of the input counters. 248 249 >>> Counter('abbb') | Counter('bcc') 250 Counter({'b': 3, 'c': 2, 'a': 1}) 251 252 ''' 253 if not isinstance(other, Counter): 254 return NotImplemented 255 result = Counter() 256 for elem, count in self.items(): 257 other_count = other[elem] 258 newcount = other_count if count < other_count else count 259 if newcount > 0: 260 result[elem] = newcount 261 for elem, count in other.items(): 262 if elem not in self and count > 0: 263 result[elem] = count 264 return result 265 266 def __and__(self, other): 267 ''' Intersection is the minimum of corresponding counts. 268 269 >>> Counter('abbb') & Counter('bcc') 270 Counter({'b': 1}) 271 272 ''' 273 if not isinstance(other, Counter): 274 return NotImplemented 275 result = Counter() 276 for elem, count in self.items(): 277 other_count = other[elem] 278 newcount = count if count < other_count else other_count 279 if newcount > 0: 280 result[elem] = newcount 281 return result 282 283 Counter 284 285 Counter
3、有序字典
orderdDict是對字典類型的補充,他記住了字典元素添加的順序
例:
dic = collections.OrderedDict() dic['k1']='v1' dic['k2']='v2' dic['k3']='v3' print(dic)
操做方法與字典操做方法相同
4、默認字典
dic=collections.defaultdict(list) dic['k1'].append('cat') print(dic)
操做方法與字典操做方法相同
5、可命名元組(namedtuple)
根據nametuple能夠建立一個包含tuple全部功能以及其餘功能的類型。
import collections Mytuple = collections.namedtuple('Mytuple',['x', 'y', 'z'])
6、隊列
雙向隊列(deque):
d = collections.deque() d.append('1') #添加數據到隊列 d.appendleft('10') #添加數據到隊列左邊 d.appendleft('1') print(d) r = d.count('1') #查看1在隊列裏的個數 print(r) d.extend(['yy','uu','ii']) #添加多個元素到列表 d.extendleft(['y1y','u1u','i1i']) #添加多個元素到列表左邊 print(d) d.rotate(5) #將右邊的值按順序放到左邊,括號裏的值爲要取值的個數 print(d)
單向隊列(queue):
import queue q = queue.Queue() q.put('123') q.put('678') #將數據添加到隊列 print(q.qsize()) #獲取隊列中數據的個數 print(q.get()) #拿取隊列中的數據(先進先出原則)
7、深淺拷貝
對於 數字 和 字符串 而言,賦值、淺拷貝和深拷貝無心義,由於其永遠指向同一個內存地址。
import copy # ######### 數字、字符串 ######### 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))
對於字典、元祖、列表 而言,進行賦值、淺拷貝和深拷貝時,其內存地址的變化是不一樣的。
賦值,只是建立一個變量,該變量指向原來內存地址,如:
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)
8、函數
1、背景
在學習函數以前,一直遵循:面向過程編程,即:根據業務邏輯從上到下實現功能,其每每用一長段代碼來實現指定功能,開發過程當中最多見的操做就是粘貼複製,也就是將以前實現的代碼塊複製到現需功能處,以下:
while True: if cpu利用率 > 90%: #發送郵件提醒 鏈接郵箱服務器 發送郵件 關閉鏈接 if 硬盤使用空間 > 90%: #發送郵件提醒 鏈接郵箱服務器 發送郵件 關閉鏈接 if 內存佔用 > 80%: #發送郵件提醒 鏈接郵箱服務器 發送郵件 關閉鏈接
仔細一看上述代碼,if條件語句下的內容能夠被提取出來公用,以下:
def 發送郵件(內容) #發送郵件提醒 鏈接郵箱服務器 發送郵件 關閉鏈接 while True: if cpu利用率 > 90%: 發送郵件('CPU報警') if 硬盤使用空間 > 90%: 發送郵件('硬盤報警') if 內存佔用 > 80%:
對於上述的兩種實現方式,第二次必然比第一次的重用性和可讀性要好,其實這就是函數式編程和麪向過程編程的區別:
函數式編程最重要的是加強代碼的重用性和可讀性
2、定義和使用
def 函數名(參數): ... 函數體 ...
函數的定義主要有以下要點:
以上要點中,比較重要有參數和返回值:
一、返回值
函數是一個功能塊,該功能到底執行成功與否,須要經過返回值來告知調用者。
def 發送短信(): 發送短信的代碼... if 發送成功: return True else: return False while True: # 每次執行發送短信函數,都會將返回值自動賦值給result # 以後,能夠根據result來寫日誌,或重發等操做 result = 發送短信() if result == False: 記錄日誌,短信發送失敗...
二、參數
爲何要有參數?
1 def 發送郵件(郵件內容) 2 3 #發送郵件提醒 4 鏈接郵箱服務器 5 發送郵件 6 關閉鏈接 7 8 9 while True: 10 11 if cpu利用率 > 90%: 12 發送郵件("CPU報警了。") 13 14 if 硬盤使用空間 > 90%: 15 發送郵件("硬盤報警了。") 16 17 if 內存佔用 > 80%: 18 發送郵件("內存報警了。")
1 def CPU報警郵件() 2 #發送郵件提醒 3 鏈接郵箱服務器 4 發送郵件 5 關閉鏈接 6 7 def 硬盤報警郵件() 8 #發送郵件提醒 9 鏈接郵箱服務器 10 發送郵件 11 關閉鏈接 12 13 def 內存報警郵件() 14 #發送郵件提醒 15 鏈接郵箱服務器 16 發送郵件 17 關閉鏈接 18 19 while True: 20 21 if cpu利用率 > 90%: 22 CPU報警郵件() 23 24 if 硬盤使用空間 > 90%: 25 硬盤報警郵件() 26 27 if 內存佔用 > 80%: 28 內存報警郵件()
函數的有三中不一樣的參數:
1 # ######### 定義函數 ######### 2 3 # name 叫作函數func的形式參數,簡稱:形參 4 def func(name): 5 print name 6 7 # ######### 執行函數 ######### 8 # 'spykdis' 叫作函數func的實際參數,簡稱:實參 9 func('spykdis')
1 def func(name, age = 18): 2 3 print "%s:%s" %(name,age) 4 5 # 指定參數 6 func('cat', 19) 7 # 使用默認參數 8 func('tom') 9 10 注:默認參數須要放在參數列表最後
1 def func(*args): 2 3 print args 4 5 6 # 執行方式一 7 func(11,33,4,4454,5) 8 9 # 執行方式二 10 li = [11,2,2,3,3,4,54] 11 func(*li)
1 def func(**kwargs): 2 3 print args 4 5 6 # 執行方式一 7 func(name='tom',age=18) 8 9 # 執行方式二 10 li = {'name':'tom', age:18, 'gender':'male'} 11 func(**li)
1 def func(*args, **kwargs): 2 3 print args 4 print kwargs
9、lambda表達式
學習條件運算時,對於簡單的 if else 語句,可使用三元運算來表示,即:
# 普通條件語句 if 1 == 1: name = 'wupeiqi' else: name = 'alex' # 三元運算 name = 'wupeiqi' if 1 == 1 else 'alex'
對於簡單的函數,也存在一種簡便的表示方式,即:lambda表達式
# ###################### 普通函數 ###################### # 定義函數(普通方式) def func(arg): return arg + 1 # 執行函數 result = func(123) # ###################### lambda ###################### # 定義函數(lambda表達式) my_lambda = lambda arg : arg + 1 # 執行函數 result = my_lambda(123)
lambda存在乎義就是對簡單函數的簡潔表示
10、內置函數
詳細見python文檔,猛擊這裏
map
遍歷序列,對序列中每一個元素進行操做,最終獲取新的序列。
1 li = [11, 22, 33] 2 3 new_list = map(lambda a: a + 100, li)
1 li = [11, 22, 33] 2 sl = [1, 2, 3] 3 new_list = map(lambda a, b: a + b, li, sl)
filter
對於序列中的元素進行篩選,最終獲取符合條件的序列
1 li = [11, 22, 33] 2 3 new_list = filter(lambda arg: arg > 22, li) 4 5 #filter第一個參數爲空,將獲取原來序列
reduce
對於序列內全部元素進行累計操做
1 li = [11, 22, 33] 2 3 result = reduce(lambda arg1, arg2: arg1 + arg2, li) 4 5 # reduce的第一個參數,函數必需要有兩個參數 6 # reduce的第二個參數,要循環的序列 7 # reduce的第三個參數,初始值