python的基础知识

本文介绍了Python编程的基础内容,包括字典操作、datetime模块的时间处理、time对象的应用,以及进阶函数如参数传递、高阶函数、生成器和全局变量的使用实例。涵盖了datetime对象的日期转换、timedelta操作,以及lambda匿名函数、map、filter、reduce等函数的实战演示。

1.dict

a = {‘cats’:4,’dogs’:2,’pigs’:7}

获取键、值

a.keys(), a.values()

获取所有的键值对

a.items()

2.datetime模块

import datetime as dt
d1 = dt.datetime(2022,08,07)
d2 = dt.datetime(2022,08,15)

转换成字符串格式

d1.strftime(%A’,%y%m%d’), Tuesday, 09/25/07
d = d2-d1, 返回的是一个timedelta对象,
d.days : 8
d.seconds: 0

查看今天的日期:dt.date.today() , 2022-08-07

datetime(year, month,day, hr, min, second, us)来创建一个datetime对象
d1 = dt.datetime().now()  # 2022-08-07 20:58:42 148000
时间加减
d2 = d1 + dt.timedelta(30)
 # 2022-09-07 20:58:42 148000

通过制定格式的字符串来创建时间

dt.datetime.strptime(2022-08-07,%m%y%d’)

#2022-08-07 00:00:00
参考:https://ailearning.apachecn.org/#/docs/da/068

4.time对象

time(hour,minute,seconds)

5.进阶函数

参数传递、高阶函数、lambda匿名函数、gblobal变量、递归.函数也是一个对象,可以将函数座位参数传递给另一个函数,将函数作为字典存储,将函数作为返回值

def square(x):
	return x*x

def cube(x):
	return x*x*x

作为字典的值

funcs = {’square’:square,’cube’:cube}
x = 2
print(square(x))
print(cube(x))

for func in sorted(funds):
	print(func, funcs[func](x)

可以作为回掉函数传第给另一个函数, 这样做的好处是,满足一个函数数据流的原子性

def funk(x):
	return x+1
def fun(x):
	return x-1
def func(x, func):
	if x>10:
		调用函数a
	if x<=10:
		调用函数b

a. map函数

map(f,sq) #将f作用到sq的每一个值上, 相当于[f(s) for s in sq]
list(map(square,range(5))) #等价于  [square(x) for x in range(5)]
#输出 [0, 1, 4, 9, 16]

b. filter函数

def is_even(x)
	return x%2==0:

[s for s in range(5) if is_even(s)]等价于
filter(is_even,range(5))
#输出:0,2,4

#一起使用 map(square, filter(is_even,range(5))), 输出:[0,4,16]

c. reduce函数
传入一个二元函数f(x,y), 并对于序列sq, 每次合并两个元素。reduce,顾名思义,减少的意思,通过对sq中的元素做某一操作,从而缩减其规模

def my_add(x,y):
	return x+y
sq = [1,2,3,4,5]
reduce(my_add, sq)

#输出:15

d. 匿名函数 lambda

s1  =map(lambda x:x*x, range(5))
s2 = reduce(lambda x,y:x+y, map(lambda x:x**2,range(1,10))

小结:
(1 )map(func,iteratorble_arr), func是函数接收一个参数,iteratorble_arr是可迭代对象,返回对象与iteratorble_arr长度一样
(2) reduce(func,iteratorble_arr), func是函数接收两个参数,iteratorble_arr是可迭代对象,返回对象与iteratorble_arr,返回的长度为iteratorble_arr的1/2
(3) filter(func,iteratorble_arr),对于iteratorble_arr中的每个元素,返回True或者False, 保留为True的元素

6.全局变量

x = 15
def print_x():
	global x
	x = 18
	print(x)

print_x() # 18
print(x) #18, 全局变量在print_x函数中被修改
x = 15
def print_x():
	x = 18
	print(x)

print_x() # 18
print(x) #15, 全局变量在print_x函数中未被修改

7.生成器

def collatz(n):
	while n != 1:
		if n%2 == 0:
			n /= 2
		else:
			n = 3*n+1
		yield n

for x in collatz(7):
	print(x)

a = collatz(7)
print(next(a))
print(next(a))

yield是懒执行的,当函数执行到yieldn, 就会返回一个n, 本次函数调用结束,等到下一次再进入函数,从yield后面继续执行。yield需要由循环(for)或者next 触发获取下一个数

a.二叉树中序遍历非递归生成器版本

def inorder(root):
	stack = []
	stack.append(root)
	#ans = []
	while let(stack) != 0 and root is not None:
		while root is not None:
			root = root
			stack.append(root)
		root = stack.pop()
		#ans.append(root.val) 
		yield root.val
		root = root.right
	#return ans
#构建树
tree = BinaryTree(
    left=BinaryTree(
        left=BinaryTree(1),
        value=2,
        right=BinaryTree(
            left=BinaryTree(3),
            value=4,
            right=BinaryTree(5)
        ),
    ),
    value=6,
    right=BinaryTree(
        value=7,
        right=BinaryTree(8)
    )
)

#调用
for value in Tree:
	print value

b.杨辉三角形

def triangles():
    result = []
    i = 1
    while True:
        a = [1]*i

        for j, val in enumerate(a):
            if j == 0 or j == len(a) - 1:
                a[j] = val
            else:
                temp = result[j] + result[j - 1]
                a[j] = temp

        yield a
        result = a
        i += 1

    return 'done'

def test_triangles():
    n = 0
    results = []

    for t in triangles(): #遍历生成器,每次返回一个列表
        results.append(t)
        n = n + 1
        if n == 10:
            break
    for t in results:
        print(t)

    if results == [

        [1],

        [1, 1],

        [1, 2, 1],

        [1, 3, 3, 1],

        [1, 4, 6, 4, 1],

        [1, 5, 10, 10, 5, 1],

        [1, 6, 15, 20, 15, 6, 1],

        [1, 7, 21, 35, 35, 21, 7, 1],

        [1, 8, 28, 56, 70, 56, 28, 8, 1],

        [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]

    ]:

        print('测试通过!')

    else:

        print('测试失败!')

test_triangles()

'''
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
'''

参考

廖雪峰python官方网站

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值