summaryrefslogtreecommitdiff
path: root/LectureNotesOnPython.rst
diff options
context:
space:
mode:
authorHui Lan <lanhui@zjnu.edu.cn>2019-05-19 22:31:11 +0800
committerHui Lan <lanhui@zjnu.edu.cn>2019-05-19 22:31:11 +0800
commitdfe3585459882f1e168e9e4f2242e7d0759a9824 (patch)
tree89538935c2cae2b8ff493ffff7cf8a5f0af5e4e5 /LectureNotesOnPython.rst
parent6636897dadc683704243ef5d51c8f1c9bb7c2c6f (diff)
LectureNotesOnPython.rst: added Conditional Expression, Generator, any and all, sets, Counter, defaultdict, keyword arguments.
Diffstat (limited to 'LectureNotesOnPython.rst')
-rw-r--r--LectureNotesOnPython.rst195
1 files changed, 195 insertions, 0 deletions
diff --git a/LectureNotesOnPython.rst b/LectureNotesOnPython.rst
index c8d4c06..eebb243 100644
--- a/LectureNotesOnPython.rst
+++ b/LectureNotesOnPython.rst
@@ -2120,7 +2120,202 @@ school.py
omg
+
+其它有用的Python语言特性
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+
+条件表达
+```````````````````````````````````````````````````
+
+把 if else 写在一行。看函数 take_log3。
+
+
+.. code:: python
+
+ import math
+
+ def take_log(x):
+ if x > 0:
+ return math.log(x)
+ else:
+ raise Exception('The input is not a positive number.')
+
+ def take_log2(x):
+ if x > 0:
+ return math.log(x)
+ else:
+ return float('nan')
+
+ def take_log3(x):
+ return math.log(x) if x > 0 else float('nan')
+
+
+
+ x = -1
+ try:
+ result = take_log(x)
+ print('result from take_log is %g.' % (result))
+ except:
+ print('x is not a good value. ')
+
+
+ result = take_log2(x)
+ print('result from take_log2 is %g.' % (result))
+ result = take_log3(x)
+ print('result from take_log3 is %g.' % (result))
+
+
+
+Generator表达
+```````````````````````````````````````````````````
+
+Generator也是一个对象,对象里面有 __iter__ 与 __next__ 方法。 当所有的元素都遍历完之后,抛出 **StopIteration** 异常。
+
+.. code:: python
+
+ g = (x**2 for x in range(3))
+
+ print(next(g))
+ print(next(g))
+ print(next(g))
+ print(next(g))
+
+
+可以用 for loop 遍历 g 中的所有元素。
+
+.. code:: python
+ g = (x**2 for x in range(3))
+
+ for x in g:
+ print(x)
+
+
+
+any 与 all
+```````````````````````````````````````````````````
+
+any/all 是个函数,可以接收 list 或 generator 类型的参数。
+
+
+.. code:: python
+
+
+ any([False, False, True]) # True
+
+ developed_countries = ['canada', 'germany', 'japan', 'uk', 'swiss', 'norway']
+
+ f = open('brexit-news.txt')
+ news = f.read()
+ f.close()
+ print( any(word.strip().lower() in developed_countries for word in news.split()) )
+ print( all(word.strip().lower() in developed_countries for word in news.split()) )
+
+
+
+集合 Sets
+```````````````````````````````````````````````````
+
+.. code:: python
+
+ set('123')
+ set([1,2,3])
+
+ def all_letters_unique(word):
+ return len(set(word)) == len(word)
+
+ def all_letters_vowel(word):
+ return set(word) <= set('aeiou')
+
+ def compare_vocaburary(a, b):
+ return set(a) > set(b)
+
+ def vocaburary_diff(a, b):
+ return list(set(a) - set(b))
+
+ def vocaburary_common(a, b):
+ return list(set(a).intersection(set(b)))
+
+ print( all_letters_unique('unique') )
+ print( all_letters_vowel('ou') )
+ print( compare_vocaburary(['he', 'knows', 'big', 'small'], ['he', 'knows', 'small']) )
+ print( vocaburary_diff(['he', 'knows', 'big', 'small'], ['he', 'knows', 'small']) )
+ print( vocaburary_common(['he', 'knows', 'big', 'small'], ['he', 'knows', 'small']) )
+
+
+
+计数 Counter
+```````````````````````````````````````````````````
+
+与字典有点像。
+
+.. code:: python
+
+
+ from collections import Counter
+
+ c = Counter('donald') # Counter({'d': 2, 'o': 1, 'n': 1, 'a': 1, 'l': 1})
+ c['d'] # 2
+ c['x'] # 0, not a KeyError
+ c.most_common() # [('d', 2), ('o', 1), ('n', 1), ('a', 1), ('l', 1)]
+
+ vote = Counter(['yes', 'no', 'yes', 'yes', 'no']) # Counter({'yes': 3, 'no': 2})
+
+
+
+defaultdict
+```````````````````````````````````````````````````
+
+可以避免第一次加 value 时 key 不在引起的 KeyError。
+
+.. code:: python
+
+ from collections import defaultdict
+
+ def seperate_odd_and_even(lst):
+ d = defaultdict(list) # the factory is list
+ for x in lst:
+ if x % 2 != 0:
+ d['odd'].append(x)
+ else:
+ d['even'].append(x)
+ return d
+
+ def unique_odd_and_even(lst):
+ d = defaultdict(set) # the factory is set
+ for x in lst:
+ if x % 2 != 0:
+ d['odd'].add(x)
+ else:
+ d['even'].add(x)
+ return d
+
+
+ result = seperate_odd_and_even([1,2,3,4,5])
+ result['odd']
+ result['even']
+
+ result2 = unique_odd_and_even([1,1,2,2,3,3])
+ result2['odd']
+ result2['even']
+
+
+收集keyword args
+```````````````````````````````````````````````````
+
+.. code:: python
+
+ def printall(*args, **kwargs):
+ print(args) # args is a tuple
+ print(kwargs) # kwargs is a dictionary
+
+
+ printall(1,2,3, a=1,b=2,c=3)
+
+
+
+
参考
------