标签:XML 迭代 done span pen abs 运算 href 大小写
(一)数据类型
(二)list、tuple、dict、set
d = {‘Michael‘: 95, ‘Bob‘: 75, ‘Tracy‘: 85}
>>> s = set([1, 1, 2, 2, 3, 3])
>>> s
{1, 2, 3}
(三)基本逻辑
循环(四)函数
def f1(a, b, c=0, *args, **kw):
print(‘a =‘, a, ‘b =‘, b, ‘c =‘, c, ‘args =‘, args, ‘kw =‘, kw)
>>> f1(1, 2, 3, ‘a‘, ‘b‘, x=99)
a = 1 b = 2 c = 3 args = (‘a‘, ‘b‘) kw = {‘x‘: 99}
(五)生成器
>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> g = (x * x for x in range(10))
方法1:使用next()
>>> next(g)
0
>>> next(g)
1
方法2:使用循环
>>> for n in g:
... print(n)
...
0
1
4
9
一般函数顺序执行,遇到return返回,
生成器在每次调用next()时执行遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return ‘done‘
(五)迭代器
可以被next()函数调用并不断返回下一个值的对象被称为迭代器,生成器都是迭代器对象。
list、tuple、dict、set、str需要使用iter()函数来变成迭代器
(六)高阶函数
map
对序列中每个元素进行操作
>>> def f(x):
... return x * x
...
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> list(r)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
reduce
>>> from functools import reduce
>>> def add(x, y):
... return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25
def is_odd(n):
return n % 2 == 1
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 结果: [1, 5, 9, 15]
>>> sorted([36, 5, -12, 9, -21])
[-21, -12, 5, 9, 36]
>>> sorted([36, 5, -12, 9, -21], key=abs)
[5, 9, -12, -21, 36]
>>> list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
[1, 4, 9, 16, 25, 36, 49, 64, 81]
标签:XML 迭代 done span pen abs 运算 href 大小写
原文地址:https://www.cnblogs.com/yuxiaowu/p/10452109.html