Pythonic与Python杂记
一、用字典映射代替switch case语句
1、switch case语句:
switch (day){
case 0:
dayName = "Sunday";
...
...
break;
case 1:
dayName = "Monday";
...
...
break;
case 2:
dayName = "Tuesday";
...
...
break;
...
default:
dayName = "Unknow";
...
...
break;
}
2、字典映射示例一:
switcher = {
0: "Sunday",
1: "Monday",
2: "Tuesday"
}
day = 0
day_name = switcher.get(day, "Unknow")
print(day_name)
运行结果:
Sunday
day = 1
day_name = switcher.get(day, "Unknow")
print(day_name)
运行结果:
Monday
day = 2
day_name = switcher.get(day, "Unknow")
print(day_name)
运行结果:
Tuesday
day = 3
day_name = switcher.get(day, "Unknow")
print(day_name)
运行结果:
Unknow
3、字典映射示例二:
def getSunday():
return "Sunday"
def getMonday():
return "Monday"
def getTuesday():
return "Tuesday"
def getDefault():
return "Unknow"
switcher = {
0: getSunday,
1: getMonday,
2: getTuesday
}
day = 0
day_name = switcher.get(day, getDefault)()
print(day_name)
运行结果:
Sunday
day = 1
day_name = switcher.get(day, getDefault)()
print(day_name)
运行法结果:
Monday
day = 2
day_name = switcher.get(day, getDefault)()
print(day_name)
运行结果:
Tuesday
day = 3
day_name = switcher.get(day, getDefault)()
print(day_name)
运行结果:
Unknow
二、列表推导式
1、示例一:
a = [1, 2, 3, 4, 5, 6, 7, 8]
list = [i*i for i in a]
print(list)
运行结果:
[1, 4, 9, 16, 25, 36, 49, 64]
2、示例二:
a = [1, 2, 3, 4, 5, 6, 7, 8]
list = [i**2 for i in a]
print(list)
运行结果:
[1, 4, 9, 16, 25, 36, 49, 64]
3、示例三:
a = [1, 2, 3, 4, 5, 6, 7, 8]
list = [i**3 for i in a]
print(list)
运行结果:
[1, 8, 27, 64, 125, 216, 343, 512]
4、示例四:
a = [1, 2, 3, 4, 5, 6, 7, 8]
list = [i**2 for i in a if i > 5]
print(list)
运行结果:
[36, 49, 64]
5、示例五:
a = {1, 2, 3, 4, 5, 6, 7, 8}
list = {i**2 for i in a if i > 5}
print(list)
运行结果:
{64, 49, 36}
6、示例六:
a = (1, 2, 3, 4, 5, 6, 7, 8)
list = (i**2 for i in a if i > 5)
print(type(list))
运行结果:
<class 'generator'>
for item in list:
print(item)
运行结果:
36
49
64
三、字典如何编写推导式
1、示例一:
students = {
"喜小乐": 18,
"石敢当": 20,
"孙悟空": 15
}
list = [key for key, value in students.items()]
print(list)
运行结果:
['喜小乐', '石敢当', '孙悟空']
2、示例二:
students = {
"喜小乐": 18,
"石敢当": 20,
"孙悟空": 15
}
list = [value for key, value in students.items()]
print(list)
运行结果:
[18, 20, 15]
3、示例三:
students = {
"喜小乐": 18,
"石敢当": 20,
"孙悟空": 15
}
list = {key: value for key, value in students.items()}
print(list)
运行结果:
{'喜小乐': 18, '石敢当': 20, '孙悟空': 15}
四、iterator(迭代器)与generator(发生器)
1、iterator:
(1) 定义:
a、迭代器是一个可以记住遍历的位置的对象;
b、迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不能后退;
c、迭代器有两个基本方法:iter() 和 next()。
(2) 示例一:
class BookCollection:
def __init__(self):
self.data = ["往事", "回味", "朝花夕拾"]
self.cur = 0
def __iter__(self):
return self
def __next__(self):
if self.cur >= len(self.data):
raise StopIteration
r = self.data[self.cur]
self.cur += 1
return r
books = BookCollection()
for book in books:
print(book)
运行结果:
往事
回味
朝花夕拾
(3) 示例二:可以使用next()函数
import sys
class BookCollection:
def __init__(self):
self.data = ["往事", "回味", "朝花夕拾"]
self.cur = 0
def __iter__(self):
return self
def __next__(self):
if self.cur >= len(self.data):
raise StopIteration
r = self.data[self.cur]
self.cur += 1
return r
books = BookCollection()
while True:
try:
print(next(books))
except StopIteration:
sys.exit()
运行结果:
往事
回味
朝花夕拾
(4) 示例三:(第二次遍历迭代器的时候不会打印值,如需多次遍历解决方案:1、实例化一个新的对象;2、使用对象拷贝的方式)
示例一:
class BookCollection:
def __init__(self):
self.data = ["往事", "回味", "朝花夕拾"]
self.cur = 0
def __iter__(self):
return self
def __next__(self):
if self.cur >= len(self.data):
raise StopIteration
r = self.data[self.cur]
self.cur += 1
return r
books = BookCollection()
for book in books:
print(book)
for book in books:
print(book)
运行结果:
往事
回味
朝花夕拾
示例二:
import sys
class BookCollection:
def __init__(self):
self.data = ["往事", "回味", "朝花夕拾"]
self.cur = 0
def __iter__(self):
return self
def __next__(self):
if self.cur >= len(self.data):
raise StopIteration
r = self.data[self.cur]
self.cur += 1
return r
books = BookCollection()
while True:
try:
print(next(books))
except StopIteration:
sys.exit()
while True:
try:
print(next(books))
except StopIteration:
sys.exit()
运行结果:
往事
回味
朝花夕拾
示例三:
import sys
class BookCollection:
def __init__(self):
self.data = ["往事", "回味", "朝花夕拾"]
self.cur = 0
def __iter__(self):
return self
def __next__(self):
if self.cur >= len(self.data):
raise StopIteration
r = self.data[self.cur]
self.cur += 1
return r
books = BookCollection()
for book in books:
print(book)
while True:
try:
print(next(books))
except StopIteration:
sys.exit()
运行结果:
往事
回味
朝花夕拾
示例四:(新实例化一个对象)
import sys
class BookCollection:
def __init__(self):
self.data = ["往事", "回味", "朝花夕拾"]
self.cur = 0
def __iter__(self):
return self
def __next__(self):
if self.cur >= len(self.data):
raise StopIteration
r = self.data[self.cur]
self.cur += 1
return r
books = BookCollection()
books_two = BookCollection()
for book in books:
print(book)
运行结果:
往事
回味
朝花夕拾
while True:
try:
print(next(books_two))
except StopIteration:
sys.exit()
运行结果:
往事
回味
朝花夕拾
示例五:(对象拷贝)
import sys
class BookCollection:
def __init__(self):
self.data = ["往事", "回味", "朝花夕拾"]
self.cur = 0
def __iter__(self):
return self
def __next__(self):
if self.cur >= len(self.data):
raise StopIteration
r = self.data[self.cur]
self.cur += 1
return r
books = BookCollection()
import copy
books_two = copy.copy(books)
for book in books:
print(book)
运行结果:
往事
回味
朝花夕拾
while True:
try:
print(next(books_two))
except StopIteration:
sys.exit()
运行结果:
往事
回味
朝花夕拾
2、generator:
(1) 在python中,使用yield的函数被称为生成器;
(2) 生成器是一个返回迭代器的函数,只能用于迭代器操作,更简单点理解生成器就是一个迭代器;
(3) 在调用生成器的过程中,每次遇到yield时函数会暂停并保存当前所有的运行信息,返回yield的值,并在下一次执行next()方法时从当前位置继续运行;
(4) 调用一个生成器函数,返回的是一个迭代器对象。
(5) 示例一:
import sys
def feibonacci(n): # 生成器函数 - 斐波那契
a, b, counter = 0, 1, 0
while True:
if counter > n:
return
yield a
a, b = b, a + b
counter += 1
f = feibonacci(10)
while True:
try:
print(next(f), end=" ")
except StopIteration:
sys.exit()
运行结果:
0 1 1 2 3 5 8 13 21 34 55
(6) 示例二:
def feibonacci(n): # 生成器函数 - 斐波那契
a, b, counter = 0, 1, 0
while True:
if counter > n:
return
yield a
a, b = b, a + b
counter += 1
f = feibonacci(10)
for i in f:
print(i)
运行结果:
0
1
1
2
3
5
8
13
21
34
55
五、None
1、""、[]、{}、()不等于None:
a = ""
b = []
c = {}
d = ()
print(a == None)
print(b == None)
print(c == None)
print(d == None)
运行结果:
False
False
False
False
print(a is None)
print(b is None)
print(c is None)
print(d is None)
运行结果:
False
False
False
False
print(type(None))
运行结果:
<class 'NoneType'>
2、示例一:
def fun():
return None
a = fun()
if not a:
print("S")
else:
print("F")
if a is None:
print("S")
else:
print("F")
运行结果:
S
S
3、判断不为空操作建议的两种方式:(1) if a: ;(2) if not a: 。
六、对象存在并不一定是True
1、示例一:
class Test():
pass
test = Test()
print(bool(test))
运行结果:
True
2、示例二:
class Test():
def __len__(self):
return 0
test = Test()
print(bool(test))
运行结果:
False
七、__len__与__bool__内置方法
1、示例一:
class Test():
def __len__(self):
print("len called")
return True
test = Test()
print(bool(test))
运行结果:
len called
True
2、示例二:
class Test():
def __bool__(self):
print("boll called")
return False
def __len__(self):
print("len called")
return True
test = Test()
print(bool(test))
运行结果:
boll called
False
八、装饰器的副作用
1、 示例一:打印函数名
# 不带装饰器
from datetime import datetime
def decorator(func):
def wrapper():
print(datetime.now())
func()
return wrapper
def f1():
print(f1.__name__)
f1()
运行结果:
f1
# 带装饰器
from datetime import datetime
def decorator(func):
def wrapper():
print(datetime.now())
func()
return wrapper
@decorator
def f1():
print(f1.__name__)
f1()
运行结果:
2019-10-02 23:17:15.278430
wrapper
2、示例二:打印help函数
# 不带装饰器
from datetime import datetime
def decorator(func):
def wrapper():
print(datetime.now())
func()
return wrapper
def f1():
"""
This is f1
:return:
"""
print(f1.__name__)
print(help(f1))
运行结果:
Help on function f1 in module __main__:
f1()
This is f1
:return:
None
# 带装饰器
from datetime import datetime
def decorator(func):
def wrapper():
print(datetime.now())
func()
return wrapper
@decorator
def f1():
"""
This is f1
:return:
"""
print(f1.__name__)
print(help(f1))
运行结果:
Help on function wrapper in module __main__:
wrapper()
None
3、解决方案:使用wraps装饰器
from datetime import datetime
from functools import wraps
def decorator(func):
@wraps(func)
def wrapper():
print(datetime.now())
func()
return wrapper
@decorator
def f1():
"""
This is f1
:return:
"""
print(f1.__name__)
print(help(f1))
运行结果:
Help on function f1 in module __main__:
f1()
This is f1
:return:
None