1.format语法
'Hello, {0}, 成绩提升了 {1:.1f}%'.format('小明', 17.125)
'Hello, 小明, 成绩提升了 17.1%'
2.循环语句
sum = 0
for x in range(101):
sum = sum + x
print(sum)
sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
print(sum)
3 abs()---去绝对值。hex()----一个整数转换成十六进制表示。
4 阶乘fact(n) = n! = 1 x 2 x 3 x ... x (n-1) x n = (n-1)! x n = fact(n-1) x n
所以,fact(n)可以表示为n x fact(n-1)
def fact(n):
if n==1:
return 1
return n * fact(n - 1)
5 切片
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
L[0:3] L[-5,-2]
['Michael', 'Sarah', 'Tracy']
6 迭代
for key in d:#输出key
print(key)
for value in d.values():#输出值
print(value)
for k,v in d.items():# 输出所有
print(k,v)
for i, value in enumerate(['A', 'B', 'C']):..print(i, value)#下标索引
0 A
1 B
2 C
7 for循环生生列表
[x * x for x in range(1, 11) if x % 2 == 0]
[4, 16, 36, 64, 100]
d = {'x': 'A', 'y': 'B', 'z': 'C' }
[k + '=' + v for k, v in d.items()]
['y=B', 'x=A', 'z=C']
8 map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。
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]
9. reduce函数
from functools import reduce
>>> def fn(x, y):..
. return x * 10 + y...
>>> reduce(fn, [1, 3, 5, 7, 9])
13579
10. filter 函数
def is_odd(n):
return n % 2 == 1
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 结果: [1, 5, 9, 15]
11.sorted函数
sorted([36, 5, -12, 9, -21])
[-21, -12, 5, 9, 36]
sorted([36, 5, -12, 9, -21], key=abs)
[5, 9, -12, -21, 36]
12.lambda 匿名函数、
list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
[1, 4, 9, 16, 25, 36, 49, 64, 81]
13.functools.partial就是帮助我们创建一个偏函数
import functools
int2 = functools.partial(int, base=2)
int2('1000000')
网友评论