一.编码问题 1.python2默认编码是ASCII,python3默认编码是UTF-8. 出现中文乱码是因为中文文件打开的时候源文件用的编码格式转换成Unicode,Unicode再转换成当前的编码格式,前后两个编码格式不同引起的。 GBK汉字和英文都占两个字节,Unicode全部占4个字节,比较浪费空间,UTF-8英文占一个字节,汉字占三个字节。 GBK 《==》 Unicode 《==》UTF-8,GBK和UTF-8之间的转换需要通过Unicode。(两种编码之间的转换,要通过Unicode作为桥梁) 2·在python2中bytes也是str类型,python3中bytes就是bytes。 二·r是用来读取非二进制文件。rb是读取二进制文件。 f_name是文件的名称及路径名,'r'是读取文件,encoding = "utf-8"是用utf-8编码的方式打开文件。
open(f_name,'r',encoding="utf-8")
二·函数基础
1.
from functools import reducedef Sum(x,y): return x+yprint(reduce(Sum,[1,2,3,4,5,6]))# from functools import reduce# a = reduce(lambda x,y:x+y,[1,2,3,4,5,6])# print(a)
2.
def file(m): with open(m,'r') as f: for n in f: print(n) file("C:/Users/Administrator/Desktop/name.txt")
3.
def Space(list): if '' in list: print("有空格") else: print("没有空格")m = [1,2,3,4,5,7]Space(m)
4.
dic = {"1": 'v1v1', "2": [1, 2, 3, 4, 5]}def Len(dic): n_dic = {} for key,value in dic.items(): if len(value) >2: value = value[0:2] n_dic[key] = value[0:2] print(value) else: n_dic[key] = valueLen(dic)
5.闭包的概念
闭包就是把子函数封装起来,返回子函数的地址。即使函数进程结束,在函数外部仍然可以调用子函数,子函数可以使用它外部函数的参数,作用域。
函数进阶
1.
def cards(): list1 = [] for k in range(2,11): list1.append(k) list1.extend(["J","Q","K","A"]) type = ["红桃","梅花","黑桃","方片"] list2 = [] for i in list1: for j in type: list2.append((i,j)) return list2print(cards())
2.
def min_max(*args): t_max = args[0] t_min = args[0] for k in args: if k <= t_min: t_min = k if k>= t_max: t_max = k return {"max":t_max,"min":t_min}print(min_max(5,2,7,8,4))
3.
def area(name,*args): def long(x,y): return x*y def square(a): return a*a def round(r): return r*r if name == "long": return long(*args) if name == "square": return square(*args) if name == "round": return round(*args)print(area("long",3,4))print(area("square",4))print(area("round",3))
4.
def calc(n): res = 1 for i in range(1, n+1, 1): res = res*i return resprint(calc(10))
5.
user_status = Falsedef login(auther_type): def travel_2(func): def travel_1(*args,**kwargs): user = 'dapeng' password = "123" global user_status if not user_status: user = input("用户名:") password = input("密码:") if user == 'dapeng' and password == "123": print("欢迎登陆") user_status = True else: print("密码错误,请重新输入") if user_status == True: func(*args, **kwargs) return travel_1 return travel_2@login("qq")def japan(travel,histroy): print("欢迎来到japan",travel,histroy)def CN(): print("欢迎来到CN")@login("wx")def AUS(renwen,histroy): print("欢迎来到AUS",renwen,histroy)japan("sakura","300")AUS("RENWU","daishu")