由于里面的大部分内容和代码都是摘自《python3》书中以及查资料所得,故为转载
前面部分是知识点,后面附所有看书时的代码,以及小练习,上传供日后参考
1、用户输入: birth = input ( ‘birth: ’ )
2、list的切片索引(tuple也属于list,也可以):
L[0:3]: 取L中的前三个元素 |
L[-2,-1]:取倒数两个数 |
L[::5]:每个5个取一个 |
L[:]:复制 |
3、迭代(字符串、list可迭代)
判断变量是否可迭代: isinstance(变量名, Iterable)
for循环中采用enumerate可同时迭代索引和元素本身:
for i,value in enumerate([‘A’,’B’,’C’]);
4、列表生成式:list(range(1,11)) === list[1,2,3,4,5,6,7,8,9,10]
for x in range(1,11): L.appeng(x*x) === [x*x for x in range(1,11)] === [1,4,9,16,…]
加入判断:[x*x for x in range(1,11) if x%2 == 0]
两层循环:[m+n for m in ‘ABC’ for n in ‘XYZ’]
5、Iterable 与 Iterator
凡是for循环的对象都是Iterable类型 |
凡是可以作用于next() 函数的对象都是Iterator类型,它们表示一个惰性计算的序列 |
集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象 |
Python的for循环本质上就是通过不断调用next()函数实现的,其中调用了iter()方法 |
6、高阶函数简介
1)变量可以指向函数 f = abs f (-10) 结果为:10 2)函数名也是变量 abs = 10 abs(-10) 结果报错 3)函数可做为另一个函数的参数传入:称为高阶函数 def add(a, b, f): return f(a) + f(b) print(add(-5, 6, abs)) 结果为:11 很神奇吧! |
7、map() 高阶函数
1) def f(x): return x * x r = map(f, [1, 3, 6, 9]) print(list(r)) r是Iterator惰性序列,故而用list返回 结果是:[1, 9, 36, 81] 2) print(list(map(str, [1, 4, 8, 4, 5]))) 结果是:['1', '4', '8', '4', '5'] |
8、reduce() 高阶函数:相当于递归的map()
from functools import reduce
def add(a, b):
return a + b
print(reduce(add, [1, 2, 3, 4, 5, 6]))
相当于1+2+3+4+5+6,结果是21
9、filter() 筛选函数:通过返回值的True还是False来判断元素的去留
def is_odd(n):
return n % 2 == 1
l = [1, 2, 3, 4, 5, 6, 7]
print(list(filter(is_odd, l)))
10、strip() 字符串去除首尾空格,可传入参数,去除首尾的某个字符
11、yield相当于return,不同的是当用next调用方法时,会从上一次yield后面接着运行程序,可以避免反复创建对象,大大节省空间
12、返回函数:将函数作为返回值
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
f = lazy_sum(1, 3, 5, 7, 9)
print(f)
print(f())
内部函数可以使用外部函数的参数和局部变量,当返回函数时,相关的变量和参数也被包含其中,此成为“闭包”
13、返回闭包时需要牢记:返回函数不要引用任何循环变量,或者后续会发生变化的变量
实在需要引用循环变量,就另外再创建一个函数
改良前:结果是9, 9, 9 def count(): fs = [] for i in range(1, 4): def f(): return i * i fs.append(f) return fs f1, f2, f3 = count() print(f1()) print(f2()) print(f3()) | 改良后:结果时1, 4, 9 def count(): def f(j): def g(): return j * j return g fs = [] for i in range(1, 4): fs.append(f(i)) return fs f1, f2, f3 = count() print(f1()) print(f2()) print(f3()) |
14、匿名函数
print(list(map(lambda x: x * x, (1, 2, 3))))
这里的lambda x: x * x 就是一个匿名函数,相当于
def f(x):
return x * x
15、装饰器:在代码运行期间动态增加功能的方式,称为“装饰器”
16、*代表将传入参数作为元祖,**代表将传入参数作为字典
17、偏函数: function.partial的作用就是把一个函数的某些参数给固定住
(也就是设置默认值),返回一个新的函数, 调用这个函数会更简单
import functools
int2 = functools.partial(int, base=2)
print(int2('1000000'))
print(int2('1000000', base=10))
代码:
# name = input()
# print(name)
# # 高阶函数
# def add(a, b, f):
# return f(a, 2) + f(b, 2)
# print(add(1, 2, pow))
# def f(x):
# return x * x
# print(list(map(f, [1, 2, 3, 4])))
# print(list(map(str, [1, 2, 3, 4])))
# 递归运算
# from functools import reduce
# def add(a, b):
# return a + b
# print(reduce(add, [1, 2, 3, 4, 5, 6]))
# def add2(a, b):
# return 10 * a + b
# print(reduce(add2, [1, 2, 3, 4, 5, 6]))
#
# def char2num(s):
# return {'0': 0,'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
#
# def str2int(s):
# return reduce(lambda x, y: x * 10 + y, map(char2num, s))
# print(str2int('123'))
# def normalize(name):
# return str(name[0]).upper() + str(name[1:]).lower()
# L1 = ['adam', 'sophia', 'LISA']
# L2 = list(map(normalize, L1))
# print(L2)
# from functools import reduce
# def sum(list):
# return reduce(lambda x, y: x + y, list)
# def prod(list):
# return reduce(lambda x, y: x * y, list)
# l = [1, 2, 3, 4]
# print('求和:', sum(l))
# print('求积:', prod(l))
# from functools import reduce
# def str2float(s):
# a = s.split('.')[0]
# b = (s.split('.')[1])
# b = b[0: b.rindex('0')]
# c = a + b
# aa = reduce(lambda x, y: 10 * x + y, list(map(int, c)))
# return float(aa) / pow(10, len(b))
# print('123.456 = ', str2float('123.405060'))
# def is_odd(n):
# return n % 2 == 1
# l = [1, 2, 3, 4, 5, 6, 7]
# print(list(filter(is_odd, l)))
#
# def not_empty(n):
# return n and str(n).strip()
# l = ['111123', 2, ' ', 4, '', None]
# print(l)
# print(list(filter(not_empty, l)))
# def foo(num):
# print("starting...")
# while num < 10:
# num = num + 1
# yield num
# for n in foo(0):
# print(n)
# 生成素数
# def _odd_iter():
# n = 1
# while True:
# n = n + 2
# yield n
#
#
# def _not_divisible(n):
# return lambda x: x % n > 0
#
#
# def primes():
# yield 2
# it = _odd_iter()
# while True:
# n = next(it)
# yield n
# it = filter(_not_divisible(n), it)
#
#
# for n in primes():
# if n < 100:
# print(n)
# else:
# break
# 过滤出回数
# def is_palindrome(n):
# if list(reversed(str(n))) == list(str(n)):
# return True
# else:
# return False
#
# print(list(filter(is_palindrome, range(11, 500))))
# L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
# def by_name(t):
# return t[0].lower()
# def by_score(t):
# return t[1]
# print(sorted(L, key=by_name))
# print(sorted(L, key=by_score, reverse=True))
# def lazy_sum(*args):
# def sum():
# ax = 0
# for n in args:
# ax = ax + n
# return ax
# return sum
# f = lazy_sum(1, 3, 5, 7, 9)
# print(f)
# print(f())
# def count():
# fs = []
# for i in range(1, 4):
# def f():
# return i * i
# fs.append(f)
# return fs
# f1, f2, f3 = count()
# print(f1())
# print(f2())
# print(f3())
# def count():
# def f(j):
# def g():
# return j * j
# return g
# fs = []
# for i in range(1, 4):
# fs.append(f(i))
# return fs
# f1, f2, f3 = count()
# print(f1())
# print(f2())
# print(f3())
# 匿名函数
# print(list(map(lambda x: x * x, (1, 2, 3))))
# def f(x):
# return x * x
# f = lambda x: x * x
# print(f)
# def log(func):
# def wrapper(*args, **kw):
# print('call %s():' % func.__name__)
# return func(*args, **kw)
# return wrapper
# @log
# def now():
# print('2019-03-13')
# print(now())
# def fun(a, **l):
# print(a)
# print(l)
# fun(1, c=1, b=2)
# def log(text):
# def decorator(func):
# def wrapper(*args, **kw):
# print('%s %s(): ' % (text, func.__name__))
# return func(*args, **kw)
# return wrapper
# return decorator
#
# @log('execute')
# def now():
# print('2019-03-14')
# print(now())
# # 此处 now的__name__变成了wrapper
# print(now.__name__)
# # 不带参
# import functools
# def log(func):
# @functools.wraps(func)
# def wrapper(*args, **kw):
# print('call %s():' % func.__name__)
# return func(*args, **kw)
# return wrapper
# 带参
# import functools
# def log(text):
# def decarator(func):
# @functools.wraps(func)
# def wrapper(*args, **kw):
# print('%s %s(): ' % (text, func.__name__))
# return func(*args, **kw)
# return wrapper
# return decarator
# @log('execute')
# def now():
# print('2019-03-14')
# print(now())
# # 此处 now的__name__变成了wrapper
# print(now.__name__)
# 同时支持传参或者不传参的装饰器
# import functools
# def log(text):
# def decorator(func):
# @functools.wraps(func)
# def wrapper(*args, **kwargs):
# if isinstance(text, str):
# print("begin call: %s %s" % (text, func.__name__))
# func(*args, **kwargs)
# print("end call: %s %s" % (text, func.__name__))
# else:
# print("begin call: %s" % (func.__name__))
# func(*args, **kwargs)
# print("end call: %s" % (func.__name__))
# return
# return wrapper
# if callable(text):
# return decorator(text)
# else:
# return decorator
#
# @log
# def f():
# print("action1")
# @log('execute')
# def f2():
# print("action2")
# print(f())
# print(f2())
# 偏函数
# import functools
# int2 = functools.partial(int, base=2)
# print(int2('1000000'))
# print(int2('1000000', base=10))
# kw = {'base': 2}
# print(int('10010', **kw))
# max2 = functools.partial(max, 10)
# # 相当于args = (10, 5, 6, 7) 将10作为最左边的参数
# print(max2(5, 6, 7))