Tools
首页
画图
音乐
采集
记事
博客
实验室
登录
lypeng
146
文章
11
分类
46
记事
分类
生活-[23]
Linux-[24]
前端-[9]
数据库-[16]
PHP-[31]
git-[7]
其他-[6]
python-[20]
算法-[4]
React-Native-[4]
中草药-[2]
广告位1
广告位2
首页
/ python
返回列表
【置顶】python学习持续更新
阅读:651
发布:2018-04-08
作者:
# python(一)基础东西 ## 一些细节 第一个Python文件:hello.py ```python # 文件头 #!/usr/bin/python3 # -*- coding: utf-8 -*- # 1.hello world print('hello world!'); # 2.keyword保留关键字 import keyword; print(keyword.kwlist); # 3.注释,#号或三个(单|双)引号 """多行注释 ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] """ # 4.缩进一致,不然报错 if 5>3: print('true'); else print('false'); # 4.多行字符串,三个单引号(''')包裹 things = '''this is a p #duo hang zi fu chuan'''; print(things); # 5.字符ascii码转换 print(ord('A')) #== 65 print(chr(65)) #== A # 6.输入输出input lastf = float(input('输入去年成绩: ')) yearf = float(input('输入今年成绩: ')) bfb = (yearf-lastf)/yearf*100 print("去年成绩:%.2f,今年成绩:%.2f,提升百分比为:%.2f%%" % (lastf,yearf,bfb)) # 7.要显示%需要,两个% # 8.运行: python3 hello.py 或者写完整: /usr/bin/python3 hello.py # 9.一行一句代码,末尾可以加分号或者不加,注意缩进 ``` ## 换pip安装源(可跳过) ## 国内源: 清华:`https://pypi.tuna.tsinghua.edu.cn/simple` 阿里云:`http://mirrors.aliyun.com/pypi/simple/` 中国科技大学 `https://pypi.mirrors.ustc.edu.cn/simple/` 华中理工大学:`http://pypi.hustunique.com/` 山东理工大学:`http://pypi.sdutlinux.org/` 豆瓣:`http://pypi.douban.com/simple/` ## 执行命令: `pip config set global.index-url http://mirrors.aliyun.com/pypi/simple` 会自动创建配置文件! # python(二)条件判断与循环(if else for while) ```python # if else ''' sg = float(input('输入身高: ')); tz = float(input('输入体重:')); bmi=tz/(sg**2); print('你的bmi指数是 : ',bmi); if bmi < 18.5: print('过轻') elif (bmi >= 18.5 and bmi <25): print('正常') elif (bmi >= 25 and bmi <28): print('过重') elif (bmi >= 28 and bmi <32): print('偏胖') else: print('该减肥了') ''' # for循环 names = ['Michael', 'Bob', 'Tracy'] for name in names: print(name) #for循环 求列表和 ''' sum=0; list=[1,2,3,4,5,6,7,8,9,10] for i in list: sum += i; print('sum is : ',sum); ''' # x=list(range(10)) range可直接生成 # print(x) ''' sum=0 for i in range(101): sum += i print('sum is : ',sum) ''' # while循环,求和 ''' sum=i=0 while i<101: sum += i i+=1 print(sum) ''' # 注意:i++无效,+=可以 L = ['Bart', 'Lisa', 'Adam'] for i in L: print('HELLO ',i) n=1 while n<=10: n+=1 if n%2==1: continue print(n) print('end') ``` # python(三)列表元组字典集合(list tuple dict set) # list列表(序列) list是一种有序的集合,可以随时添加和删除其中的元素,元素可以重复 ## 序列定义 x = ['1','2','3','4','5']; x = [1,2,3,4,5] x = ['字符串',[2,2,2,3],3,4,5] //可以嵌套list ## 序列调用 x[下标] x[起始位置:结束位置] x[起始位置:结束位置:递增值] x=[0,1,2,3,4,5,6,7,8,9] x[0] = 0 x[3:] = [3,4,5,6,7,8,9] x[1:3] = [1,2] 可以将原list插空隔板,将隔板位置理解为索引位置,即一个索引一个值,原list做如下转变 **0** **1** **2** **3** **4** **5** **6** **7** **8** **9** //原list | **0** | **1** | **2** | **3** | **4** | **5** | **6** | **7** | **8** | **9** //插隔板 0 **0** 1 **1** 2 **2** 3 **3** 4 **4** 5 **5** 6 **6** 7 **7** 8 **8** 9 **9** //隔板转换为索引 1 **1** 2 **2** 3 //取1与3索引之间的值 x[0:-1] = [0, 1, 2, 3, 4, 5, 6, 7, 8] //-1即最后一个位置(索引),等价与9 x[0:9] x[-3:] = [7,8,9] //-3倒数第三个索引,即7,x[7:],从7取值到结束,不是x[7:9] x[0:3:2] = [0,2] x[1:3:2] = [1] x[::2] = [0,2,4,6,8] ## 序列赋值 x[0]=8 x[1]=[2,3,4] x[0:1]=[3] x[0:1]=[3] x[::2]=[99,99,99,99,99] #x将变为: [99, 1, 99, 3, 99, 5, 99, 7, 99, 9] ## 一些运算 sum(x) min(x) max(x) len(x) ## 其他方法 x.append(var) #追加元素,var可以是数值,字符串,列表 x.insert(index,var) #两个参数非空,必须指定index,否则报错 x.pop(var) #var为空返回最后一个元素,并从list中删除之,var不为空则返回指定下标的值,不存在下标时报错:pop index out of range x.remove(var) #删除第一次出现的该元素 x.count(var) #该元素在列表中出现的个数 x.index(var) #该元素的位置,无则抛异常 x.extend(list6) #追加list6,即合并list到x上,这里注意,使用extend函数可以一次在一个列表中插入任意多个值,而不必须每次只使用append()一次一值的插入 x.sort() #排序 x.reverse() #倒序 x.clear() #清空 del x[1] #删除指定下标的元素 del x[1:3] #删除指定下标范围的元素 ## 复制list: x1 = x #x1为x的别名,用C来说就是指针地址相同,对x1操作即对x操作。 x1 = x[:] #x1为x的克隆,即另一个拷贝。 ## 输出example ```python L = [ ['Apple', 'Google', 'Microsoft'], ['Java', 'Python', 'Ruby', 'PHP'], ['Adam', 'Bart', 'Lisa'] ] # 打印Apple: print(L[0][0]) # 打印Python: print(L[1][1]) # 打印Lisa: print(L[2][2]) ``` ------------ # tuple元组 声明,用一个小括号 lastname=('li','zhang','liu'); tuple和list非常类似,但是tuple一旦初始化就不能修改,它也没有append(),insert()这样的方法。 其他获取元素的方法和list是一样的,你可以正常地使用classmates[0],classmates[-1],但不能赋值成另外的元素。 不可变的tuple有什么意义?因为tuple不可变,所以代码更安全。如果可能,能用tuple代替list就尽量用tuple。 tuple所谓的“不变”是说,tuple的每个元素,指向永远不变。即指向'a',就不能改成指向'b',指向一个list,就不能改成指向其他对象,但指向的这个list本身是可变的! tuple的陷阱: 1. 当你定义一个tuple时,在定义的时候,tuple的元素就必须被确定下来; 2. 定义只有一个元素的Tuple的时候,需要这样: tuple1 = (123,) 后面要加上一个逗号,这是因为括号()既可以表示tuple,又可以表示数学公式中的小括号,这就产生了歧义。 tuple2 = (123) #如果你这样定义你定义的将是123这个元素,而不是一个元组。 python在显示只有1个元素的tuple时,也会加一个逗号,,以免你误解成数学计算意义上的括号。 元组中的元素值是不允许修改的,但我们可以对元组进行连接组合: ``` >>> t1 = ('wuyanl','luoting','aimeiyu') >>> t2 = (1,2,3,4,5,6,7,8,9,0) >>> t1 ('wuyanl', 'luoting', 'aimeiyu') >>> t2 (1, 2, 3, 4, 5, 6, 7, 8, 9, 0) >>> t3 = t1 +t2 >>> t3 ('wuyanl', 'luoting', 'aimeiyu', 1, 2, 3, 4, 5, 6, 7, 8, 9, 0) ``` 元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组。例如:del t3 元组的内置函数: 1. 比较两个元组元素:cmp(tuple1,tuple2)相等的话返回0,不相等返回1; 2. 计算元组的长度:len(tuple) 3. 返回元组中的最大值最小值:max(tuple),min(tuple); 4. 将列表转换成元组:Tuple = tuple(list)。 -------------- # dict字典 类似json,redis,key-value库方式 与列表区别:字典是无序的,在字典中通过键来访问成员。 字典是可变的,可以包含任何其他类型 常用字典操作: dic.get(k,v)获得键k的值,第二个参数为默认值 dic.pop(k)删除键k dic.update()更新成员,若成员不存在,相当于加入 dic.keys()获得键的列表 dic.values()获得值的列表 dic.items()获得由键和值组成的列表 dic.clear()清空字典 dic.copy()复制字典 ``` >>> score={'zhang':80,'liu':90,'ma':85} >>> score['zhang'] 80 >>> score.get('zhang') 80 >>> score.get('li') >>> score.get('li',100) 100 >>> score.keys() dict_keys(['liu', 'zhang', 'ma']) >>> score.values() dict_values([90, 80, 85]) >>> score.pop('ma') 85 >>> score {'liu': 90, 'zhang': 80} >>> score.update({'zhou':99}) >>> score {'liu': 90, 'zhang': 80, 'zhou': 99} >>> score.update({'zhang':88}) >>> score {'liu': 90, 'zhang': 88, 'zhou': 99} >>> score.items() dict_items([('liu', 90), ('zhang', 88), ('zhou', 99)]) >>> l = score.items() >>> l dict_items([('liu', 90), ('zhang', 88), ('zhou', 99)]) >>> l[0] Traceback (most recent call last): File "
", line 1, in
l[0] TypeError: 'dict_items' object does not support indexing >>> l = list(score.items()) >>> l [('liu', 90), ('zhang', 88), ('zhou', 99)] >>> l[0] ('liu', 90) ``` > 需要将items对象转换为list后,调用才不会报错~ > > In Python 2.x, G.keys() returns a list, but Python 3.x returns a dict_keys object instead. The solution is to wrap G.keys() with call to list(), to convert it into the correct type # set集合 set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。 ## 声明定义 ``` #定义一个集合 >>> set1 = {1, 2, 3, 4, 5} >>> set1 {1, 2, 3, 4, 5} # 或者使用 set 函数 >>> list1=[6,7,7,8,8,9] >>> set2=set(list1) >>> set2 {8, 9, 6, 7} ``` ## 增加与删除 删除不存在的值会报错~ ``` >>> set2.add(10) >>> set2 {8, 9, 10, 6, 7} >>> set2.remove(2) Traceback (most recent call last): File "
", line 1, in
set2.remove(2) KeyError: 2 >>> set2.remove(7) >>> set2 {8, 9, 10, 6} ``` ## 交并集操作 set可以看成数学意义上的无序和无重复元素的集合,因此,两个set可以做数学意义上的交集、并集等操作: ``` >>> set1 {1, 2, 3, 4, 5} >>> set2 {8, 9, 10, 6, 7} >>> set1 & set2 set() >>> set1 | set2 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} >>> ``` ``` ## 所有方法(所有的集合方法): s.issubset(t) #如果s是t的子集,返回True,否则返回False s.issuperset(t) #如果s是t的超集,返回True,否则返回False s.union(t) #返回一个新集合, 该集合是s和t的并集 s.intersection(t) #返回一个新集合, 该集合是s和t的交集 s.difference(t) #返回一个新集合, 该集合是s的成员, 但不是t的成员, 即返回s不同于t的元素 s.symmetric_defference(t) #返回所有s和t独有的(非共同拥有)元素集合 s.copy() #返回一个s的浅拷贝, 效率比工厂要好 ## 方法(仅适用于可变集合):以下方法参数必须是可哈希的 s.add(obj) #在集合s中添加对象obj s.remove(obj) #从集合s中删除对象obj,如果obj不是集合s中的元素(obj not in s),将引发keyError错误 s.pop() #删除集合s中得任意一个对象,并返回它 s.clear() #删除集合s中的所有元素 s.update(t) #用t中的元素 修改s,即s现在包含s或t的成员 s.intersection_update(t) #s中的成员是共同属于s和t的元素 s.difference_update(t) #s中的成员是属于s但不包含在t中的元素 s.symmetric_difference_update(t) #s中的成员更新为那些包含在s或t中,但不是s和t共有的元素 s.discard(obj) #如果obj是集合s中的元素,从集合s中删除对象obj ## 集合有并集,交集,求差操作 ## 并集:intersection() 方法返回一个新集合,包含在两个集合中同时出现的所有元素。 ## 交集:union() 方法返回一个新集合,包含在两个 集合中出现的元素。 ## 差集:difference() 方法返回的新集合中,包含所有在 集合A出现但未在集合B中的元素。 ## symmetric_difference() 方法返回一个新集合,包含所有只在其中一个集合中出现的元素。 # 删除元素 set2.discard(6) # 当元素不存在时,不会引发异常 set2.remove(6) # 与discard的区别在于,如果没有要删除的元素,remove会引发一个异常 set2.pop() # 因为set是无序的,所以pop会随机的从set中删除一个元素 ``` 参考文章: 1. https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000?_blank 2. https://blog.csdn.net/liuyanfeier/article/details/53731239?_blank # python(四)列表元组字典集合复习and区别与相互转换 ## 区别 | | 列表 | 元组 | 集合 | 字典 | | --- | --- | --- | --- | --- | | 英文 | list | tuple | set | dict | | 可否读写 | 读写 | 只读 | 读写 | 读写 | | 可否重复 | 是 | 是 | 否 | 是 | | 存储方式 | 值 | 值 | 键(不能重复) | 键值对(键不能重复) | | 是否有序 | 有序 | 有序 | 无序 | 无序 | | 定义 | `[1,'a']` | `('a', 1)` | `set([1,2])` 或 `{1,2}` | `{'a':1,'b':2}` | | 添加 | `insert append` | 只读 | `s.add(3)` | `d['key'] = 'value'` | | 删除 | `pop(索引)` | `整个删除 del t` | `s.remove(55) s.pop()随机删 s.clear()清空` | `d.pop(key)` | | 修改 | `l[0]=5` | 只读 | 无 | `d['key'] = 'value' d.update({'a':5})` | | 查询 | `l[2:]` | `t[0]` | 无 | `d['a']` `score.get('zhang')` | ## 复习 抛开上篇文章,再次实战,巩固下,把能想到的大概过一遍: ### 列表list ```python #增加值,往后面追加(append),或者中间位置插入(insert) #补充------------------------------------------ >>> list2.insert(1,'555') //第一个参数索引位置,第二个参数插入值 >>> list2 ['a', '555', 'b', 'c', 'd', 'dddd', 'f', 'g'] #------------------------------------ >>> list1=[1, 2, 3, 4] >>> list1.append(['g',888]) >>> list1 [1, 2, 3, 4, ['g', 888]] >>> a=456 >>> list1.append(a) >>> list1 [1, 2, 3, 4, ['g', 888], 456] >>> list1.append('a') >>> list1 [1, 2, 3, 4, ['g', 888], 456, 'a'] >>> list1[0]=999 >>> list1 [999, 2, 3, 4, ['g', 888], 456, 'a'] #修改,像数组赋值一样 #删除,删除第几个用索引 pop #排序,只能对相同类型的元素排序,即都是数字,或都是字符串,否则报错 >>> list1 [2, 3, 4, 999, ['g', 888], 456, 'a'] >>> list1.sort() Traceback (most recent call last): File "
", line 1, in
list1.sort() TypeError: unorderable types: list() < int() >>> list1.pop(4) ['g', 888] >>> list1 [2, 3, 4, 999, 456, 'a'] >>> list1.sort() Traceback (most recent call last): File "
", line 1, in
list1.sort() TypeError: unorderable types: str() < int() >>> list1 [2, 3, 4, 456, 999, 'a'] >>> list1.pop() 'a' >>> list1.sort() >>> list2=['a','b','c','g','d','a','f'] >>> list2.sort() >>> list2 ['a', 'a', 'b', 'c', 'd', 'f', 'g'] >>> list2[0]='dddd' >>> list2 ['dddd', 'a', 'b', 'c', 'd', 'f', 'g'] >>> list2.sort() >>> list2 ['a', 'b', 'c', 'd', 'dddd', 'f', 'g'] >>> ``` ### 元组tuple ```python #定义 >>> t = (1,2,3) #想不起来有什么操作,增加试试 >>> t.add(4) Traceback (most recent call last): File "
", line 1, in
t.add(4) AttributeError: 'tuple' object has no attribute 'add' >>> t.insert(4) Traceback (most recent call last): File "
", line 1, in
t.insert(4) AttributeError: 'tuple' object has no attribute 'insert' # tuple对象没有add与insert方法,新增行不通,增删改查都试试,来修改 # 其他的报错不粘贴了,只有查,只能读取内容 >>> t[0] 1 # 可以整个删除 >>> del t # 多个tuple可以连接 >>> t1=(2,2,3,4) >>> t2=(5,5,6,6) >>> t3=t1+t2 >>> t3 (2, 2, 3, 4, 5, 5, 6, 6) # 统计个数,返回第一次出现的索引 >>> t3.count(6) 2 >>> t3.index(5) 4 # 其他几个函数 >>> len(t3) 8 >>> min(t3) 2 >>> max(t3) 6 >>> list(t3) [2, 2, 3, 4, 5, 5, 6, 6] ``` ### 字典 ```python >>> dic1={'b': 2, 'a': 1, 'd': 4, 'c': 3} # 增删改查如下 >>> dic1['f']=8 >>> dic1.pop('a') >>> dic1.update({'f':99}) >>> dic1 {'d': 4, 'c': 3, 'b': 2, 'f': 99} >>> dic1['f']=888 # 其他 # dic1.keys(),dic1.items() ``` ### 集合 ```python # 不重复 >>> s = {2,2,2,2,4,4,3,1,55,6,777} >>> s {1, 2, 3, 4, 6, 777, 55} # 集合里面只能新增单个值或者元组,不能新增list或嵌套集合 >>> s.add(6,7,8,9) Traceback (most recent call last): File "
", line 1, in
s.add(6,7,8,9) TypeError: add() takes exactly one argument (4 given) >>> s.add((6,5,4)) >>> s {1, 2, 3, 4, 5, 6, 777, 55, (6, 5, 4)} >>> s.add({5,8,9}) Traceback (most recent call last): File "
", line 1, in
s.add({5,8,9}) TypeError: unhashable type: 'set' >>> s {1, 2, 3, 4, 5, 6, 777, 55, (6, 5, 4)} >>> s.add([88,99]) Traceback (most recent call last): File "
", line 1, in
s.add([88,99]) TypeError: unhashable type: 'list' # 删除 # pop() 随机删 # remove(55) 指定元素删 # 并集交集 # s1 & s2 s1|s2 ``` ## 转换 ### 1、列表元组转其他 ```python # 列表转集合(去重) list1 = [6, 7, 7, 8, 8, 9] set(list1) # {6, 7, 8, 9} #两个列表转字典 list1 = ['key1','key2','key3'] list2 = ['1','2','3'] dict(zip(list1,list2)) # {'key1': '1', 'key2': '2', 'key3': '3'} #嵌套列表转字典 list3 = [['key1','value1'],['key2','value2'],['key3','value3']] dict(list3) # {'key3': 'value3', 'key1': 'value1', 'key2': 'value2'} # 再次体现字典是无序的 # 列表、元组转字符串 >>> list2 = ['a','a','b'] >>> mm = "222".join(list2) >>> mm 'a222a222b' >>> nn = ''.join(list2) >>> nn 'aab' tup1 = ('a', 'a', 'b') ''.join(tup1) # 'aab ``` ### 2、字典转其他 ```python # 字典转换为字符串 >>> dic1 = {'a':1,'b':2} >>> str(dic1) "{'b': 2, 'a': 1}" # 字典key和value互转(原文a_dict写错了,应该是dic2) >>> dic2 = {'a': 1, 'b': 2, 'c': 3} >>> {value:key for key, value in a_dict.items()} Traceback (most recent call last): File "
", line 1, in
{value:key for key, value in a_dict.items()} NameError: name 'a_dict' is not defined >>> {value:key for key, value in dic2.items()} {1: 'a', 2: 'b', 3: 'c'} ``` ### 3、字符串转其他 ```python # 字符串转列表 s = 'aabbcc' list(s) # ['a', 'a', 'b', 'b', 'c', 'c'] # 字符串转元组 tuple(s) # ('a', 'a', 'b', 'b', 'c', 'c') # 字符串转集合 set(s) # {'a', 'b', 'c'} # 字符串转字典 dic2 = eval("{'name':'ljq', 'age':24}") # 切分字符串 a = 'a b c' a.split(' ') # ['a', 'b', 'c'] ``` ## 二、字典的分割、合并 ```python #分割: >>> base = {'A':1, 'B':2, 'C':3, 'D':4, 'E':5} >>> subkey = ['C', 'E'] >>> subdict=dict([(key, base[key]) for key in subkey]) >>> subdict {'C': 3, 'E': 5} #合并: #方式一: >>> d1={'user':'root','pwd':'1234'} >>> d2={'ip':'127.0.0.1','port':8080} >>> dict(d1, **d2) {'port': 8080, 'ip': '127.0.0.1', 'user': 'root', 'pwd': '1234'} #为什么要加两个*号 #class dict(mapping, **kwarg),第一个参数叫位置参数,第二个叫关键字参数 # dict(d1, **d2) 先生成一个字典d1,然后把字典d2合并到d1去,如果键存在,则覆盖,如下 >>> d3={'user':'zhangsan','pwd':'123456'} >>> d4={'pwd':'888888'} >>> dict(d3,**d4) {'user': 'zhangsan', 'pwd': '888888'} #方式二: d1={'user':'root','pwd':'1234'} d2={'ip':'127.0.0.1','port':8080} d3={} for k,v in d1.items(): d3[k] = v for k,v in d2.items(): d3[k] = v print(d3) ``` ## 三、list分割、合并 ```python a=[1,2,3,4,5,6] b=['a','b','c','d'] print(a+b) a=[1,2,3,4,5,6] b=['a','b','c','d'] a+=b print(a) a=[1,2,3,4,5,6] b=['a','b','c','d'] a.extend(b) print(a) a=[1,2,3,4,5,6] b=['a','b','c','d'] a[0:0]=b #把b添加到a的最前面,和extend正好相反 print(a) li = ['a','b','c'] res1=';'.join(li) res2=''.join(res1).split(';') ``` 参考文章:https://www.cnblogs.com/louis-w/p/8391147.html?_blank # python(五)函数 # 函数 ## 基础 先来一个最简单的函数 根据半径r,计算圆面积s ```python # 定义 def s(r): return 3.14*pow(r,2) # 调用 print('半径为3的圆面积是:'.s(3)) ``` 函数的基本流程,传递参数--》计算处理--》返回值 ## 接下来说参数: 参数的类型有这些:位置参数,默认参数,可变参数,关键字参数,命名关键字参数 ### 位置参数:即常见的s(r)中的r ### 默认参数:即给个默认值s(r=3) ### 可变参数:一个星号,即参数个数是不确定的,例如计算a^2+b^2+...+n^2,def calc(*numbers) ```python def calc(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum ``` ### 关键字参数:两个星号def funname(**kw),关键字参数需要传递字典类型 ```python def person(name, age, **kw): print('name:', name, 'age:', age, 'other:', kw) # 调用 person('zhangsan',22,**{'sex':'man','job':'student'}) ``` ### 命名关键字参数: 指定接受的关键字参数名称,用一个星号分开 ```python def person(name, age, *, city, job): print(name, age, city, job) # 调用 >>> person('Jack', 24, city='Beijing', job='Engineer') Jack 24 Beijing Engineer ``` ### 参数组合 在Python中定义函数,可以用必选参数、默认参数、可变参数、关键字参数和命名关键字参数,这5种参数都可以组合使用。但是请注意,参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数。 ```python def f1(a, b=2, *c, *, d, **kw): print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw) # 调用 f1(8,8,(2,3,4),{'d':2},{'city':'beijing','area':'fangshan'}) #报错了,似乎不能这么写,重来 # 函数fa,位置参数+可变参数+关键字参数 >>> def fa(a,*b,**kw): print('a =', a, 'b =', b, 'kw =', kw) >>> fa(1,'a','b',3,8,**{'zi':'dian'}) a = 1 b = ('a', 'b', 3, 8) kw = {'zi': 'dian'} # 参数二,位置参数+命名关键字参数+关键字参数(后面两种可以合并到一个dict传递) >>> def fb(a,*,b,**kw): print('a =', a, 'b =', b, 'kw =', kw) >>> fb(1,**{'b':'aaa'},**{'zi':'dian'}) a = 1 b = aaa kw = {'zi': 'dian'} >>> fb(1,**{'b':'aaa','zi':'dian'}) a = 1 b = aaa kw = {'zi': 'dian'} ``` ##函数练习 ### 递归 ```python def fact(n): if n==1: return 1 return n * fact(n - 1) print(len(str(fact(100)))) ``` ### 计算方程组的解 ```python import math def quadratic(a,b,c): try: a = float(a) b = float(b) c = float(c) except Exception: return "对不起,a,b,c必须是数字" if a==0: return 'a不能等于0' dt=pow(b,2)-4*a*c if dt>0: x=(-b+math.sqrt(dt))/(2*a) y=(-b-math.sqrt(dt))/(2*a) return ('方程组有两个解,分别为:x1=%.1f,x2=%.1f' %(x,y)) elif dt==0: x=(-b+math.sqrt(dt))/(2*a) return ('方程组有一个解:x1=x2=%.1f' % x) else: return '方程组无解' a=input('请输入a:') b=input('请输入b:') c=input('请输入c:') x=quadratic(a,b,c) print(x) ``` ### 找列表中的最大值与最小值 ```python def findMinAndMax(L): if not isinstance(L,list): return (None, None) if len(L)==0: return (None, None) min = L[0] max = L[0] for i in L: if i>max : max = i; if i
=self.start: yield t t -= self.step for i in FloatIter(1.0,4.0,0.5):print(i) for i in reversed(FloatIter(1.0,4.0,0.5)):print(i) ``` ## 其他属性 ```python # getattr()、setattr()以及hasattr() >>> class MyObject(object): ... def __init__(self): ... self.x = 9 ... def power(self): ... return self.x * self.x ... >>> obj = MyObject() >>> hasattr(obj, 'x') # 有属性'x'吗? True >>> obj.x 9 >>> hasattr(obj, 'y') # 有属性'y'吗? False >>> setattr(obj, 'y', 19) # 设置一个属性'y' >>> hasattr(obj, 'y') # 有属性'y'吗? True >>> getattr(obj, 'y') # 获取属性'y' 19 >>> obj.y # 获取属性'y' 19 >>> getattr(obj, 'z', 404) # 获取属性'z',如果不存在,返回默认值404 404 ``` ----------- # 文件读写 ```python #!/usr/bin/python3 # -*- coding: utf-8 -*- # 文件操作 # filepath = '/home/wwwroot/test/python/w.txt' # f = open(filepath,'r',encoding='utf-8',errors='ignore') # f.read() # f.clode() # try: # f = open(filepath, 'r') # print(f.read()) # finally: # if f: # f.close() # with open(filepath, 'r') as f: # print(f.read()) # 调用read(size)方法,每次最多读取size个字节的内容。 # 调用readline()可以每次读取一行内容, # 调用readlines()一次读取所有内容并按行返回list。 # with open(filepath, 'r') as f: # print(f.readline()) #读取一行 # 'a'是追加,w+不起作用 # 'r' open for reading (default) # 'w' open for writing, truncating the file first # 'x' open for exclusive creation, failing if the file already exists # 'a' open for writing, appending to the end of the file if it exists # 'b' binary mode # 't' text mode (default) # '+' open a disk file for updating (reading and writing) # 'U' universal newlines mode (deprecated) # with open('/home/wwwroot/test/python/w.txt','a') as f: # f.write('write file learning222...') # f.close() # with open(filepath, 'r') as f: # for line in f.readlines(): # print(line.strip()) # StringIO # >>> from io import StringIO # >>> f = StringIO() # >>> f.write('hello') # 5 # >>> f.write(' ') # 1 # >>> f.write('world!') # 6 # >>> print(f.getvalue()) # hello world! # 目录操作 # >>> os.mkdir('/home/wwwroot/test/ttt') # >>> os.path.abspath('.') # '/home/lypeng' # os.rmdir('/home/wwwroot/test/ttt') # >>> os.path.split('/home/wwwroot/test/python/k.txt') # ('/home/wwwroot/test/python', 'k.txt') # >>> os.path.splitext('/home/wwwroot/test/python/k.txt') # ('/home/wwwroot/test/python/k', '.txt') # # 对文件重命名: # >>> os.rename('test.txt', 'test.py') # # 删掉文件: # >>> os.remove('test.py') # 显示当前目录下后缀是.py的文件 # [x for x in os.listdir('.') if os.isfile(x) and os.splitext(x)[1]=='.py'] #json与字典转换,json.dumps(dict);json.loads(str) >>> import json >>> d = dict(name='Bob', age=20, score=88) >>> json.dumps(d) '{"age": 20, "score": 88, "name": "Bob"}' >>> json_str = '{"age": 20, "score": 88, "name": "Bob"}' >>> json.loads(json_str) {'age': 20, 'score': 88, 'name': 'Bob'} ``` # 发邮件 安装模块 `pip3 install yagmail` 具体说明参见:https://github.com/kootenpv/yagmail?_blnak ```python #!/usr/bin/python3 # -*- coding: utf-8 -*- import yagmail yag = yagmail.SMTP(user='893371810@qq.com', password='mima', host='smtp.qq.com', port='465') # contents = ['html', '/home/wwwroot/dpshop/a.mp3'] yag.send('893371810@qq.com', "subjects", '
This is the body, and here is just text
') # 发送给谁可以写多个,用list或者tuple,contents可以是个list,可以是字符串,HTML,本地文件绝对地址,如果有本地元素且文件存在,会被当做附件,否则当字符串处理 ```
------本文结束
感谢阅读------
上一篇:没有了
下一篇:
python(二)条件判断与循环(if else for while)