# python study day3
# 高级特性 迭代
# 作用于 for 循环,循环一个可迭代对象、如dict、str字符串
# d = {'a': 1, 'b': 2, 'c': 3}
# for key in d: # 迭代dict的key
# print(key)
# for value in d.values(): # 迭代dict的value
# print(value)
# for k, v in d.items(): # 迭代dict的key、value
# print(k, v)
# 判断可迭代对象,使用collections模块的Iterable类型
# from collections import Iterable # 弃用
# from collections.abc import Iterable
# s = isinstance('123', Iterable)
# s2 = isinstance(123, Iterable)
# print(s, s2) #>>> True False
# enumerate list 的下标索引迭代
# for i, per in enumerate(['a', 'b', 'c']):
# print(i, per)
# def findMinAndMax(L):
# if len(L) == 0:
# return tuple([None, None])
# elif len(L) == 1:
# return tuple([L[0], L[0]])
# else:
# min = max = L[0]
# for per in L:
# if min > per:
# min = per
# if max < per:
# max = per
# return tuple([min, max])
# def findMinAndMax2(L):
# if len(L) == 0:
# return (None, None)
# else:
# Min = Max = L[0]
# for per in L:
# Min = min(Min, per)
# Max = max(Max, per)
# return (Min, Max)
# print(findMinAndMax2([2]))
# 列表生成式,动态编程式生成list列表
# [表达式 [, for 循环] [, 条件过滤]]
# print(list(range(1, 11))) #>>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# l1 = [x*x for x in range(1, 11)]
# print(l1) #>>> [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# [x*x for x in range(1,11) if x%2 == 0] # 添加if过滤,不能有else
# [m+n for m in 'abc' for n in '123'] # 多重for
# import os
# l = [d for d in os.listdir('.')] # os.listdir() 列出文件和目录
# print(l) # >>>['DLLs', 'Doc', 'include', 'Lib', 'libs',
#'LICENSE.txt', 'NEWS.txt', 'python.exe', 'python3.dll',
#'python38.dll', 'pythonw.exe', 'Scripts', 'tcl', 'Tools',
#'vcruntime140.dll']
# d = {1: 'A', 2: 'B', 3:'C'}
# l = [str(k)+'-'+v.lower() for k, v in d.items()]
# print(l) #>>> ['1-a', '2-b', '3-c']
# [x if x%2 == 0 else -x for x in range(1, 11)] # if
# 生成器(generator),边循环便计算、需要元素的时候才计算生成(不占用空间)
# g = (x*x for x in range(10))
# print(g) #>>> <generator object <genexpr> at 0x00000270246E8660>
# next(g) # 可以获取generator的下一个返回值,没有时抛出StopIteration错误
# for per in g: # 循环输出
# print(per)
# generator函数,包含yield关键字。遇到yield返回,再次执行会从yield处继续
# 斐波拉契数列generator函数
# def fib(max):
# n, a, b = 0, 0, 1
# while n < max:
# yield b
# a, b = b, a+b # a=b;b=a+b
# n = n + 1
# return 'done'
# g = fib(6)
# while True:
# try:
# x = next(g)
# print('g:', x)
# except StopIteration as e: # 捕获异常
# print('Generator return value:', e.value)
# break
# genertator函数遇到return、或者执行到最后一行结束
# generator函数调用返回的是一个generator对象,通过next(),for获取值
# 杨辉三角
# def triangles():
# L = [1]
# while True:
# yield L
# L = [1 if (i==0 or i==len(L)) else L[i-1]+L[i] for i in range(len(L)+1)]
# g = triangles()
# for i in range(8):
# print(next(g))
# 凡是可作用于for循环的对象都是Iterable类型
# 凡是可作用于next()函数的对象都似乎Iterator类型,它表示一个惰性计算序列
# 集合数据类型如list、dict、str 等是Iterable但不是Iterator, 可以通过iter()
# 函数获得一个Iterator对象
# python的for循环实际上是通过不断调用next()函数实现的,例如:
# for x in [1,34,53,333]:
# pass
# it = iter([1,34,53,333])
# while True:
# try:
# x = next(it)
# except StopIteration:
# break
# 函数式编程:函数之间组合调用,传递
# def plus(a, b):
# return a+b
# def compose(func, array):
# return func(array[0], array[1])
# result = compose(plus, [1, 2])
# print(result) #>>> 3
# 变量可以指向函数,函数名是变量
# a = abs
# abs = 10
# 把函数作为参数传入,这样的函数称为高阶函数
# 高阶函数 map();map(函数, Iterable) >>> 返回一个新的Iterator
# r = map(lambda x: x**2, [1, 2, 3, 4, 5]) # 计算f(x)=x*x
# print(list(r)) #>>>[1, 4, 9, 16, 25]
# list(map(str, [2, 3, 4, 5, 7])) # 数字转字符串
# reduce()函数;累积层级计算
# reduce(f, [x1, x2, x3, x4]) # =f(f(f(x1, x2), x3), x4)
# from functools import reduce
# r = reduce(lambda x, y: x*10+y, [1, 3, 5, 7, 9])
# print(r) #>>> 13579
# from functools import reduce
# DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4,
# '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
# def char2num(s):
# return DIGITS[s]
# def str2int(s):
# return reduce(lambda x, y: x*10+y, map(char2num, s))
# print(str2int('1233') + 1) #>>> 1234
# from functools import reduce
# DIGIT = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4,
# '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
# def str2float(s):
# point = s.index('.')
# pre = s[:point]
# suf = s[point+1:] # s1, s2 = s.split('.')
# num1 = str1int(pre)
# num2 = str1int(suf)
# return num1 + num2 * pow(10, -len(suf))
# def str1int(s):
# return reduce(lambda x,y: x*10+y, list(map(lambda c: DIGIT[c], s)))
# print(str2float('23.211') + 1)
# print(isinstance(str2float('23.211'), float))
廖雪峰Python学习笔记day3
最新推荐文章于 2021-02-17 00:56:43 发布
本文深入探讨了Python的高级特性,包括迭代器的概念及其应用、列表生成式的使用技巧、生成器的功能与实现方式,并介绍了如何利用高阶函数进行函数式编程。

1456

被折叠的 条评论
为什么被折叠?



