第6次全天课笔记-20180819
?第6次全天課筆記 20180819
?
習題:
找到列表中第二大的數,可以用多種方法解決。
?
思路1:
找到最大的,刪除掉,再找最大的
list1 = [5,8,9,34,214,54,22]list1_max = max(list1) print(list1_max) list1.remove(list1_max)list1_max = max(list1) print(list1_max)?
思路2:
排好序找倒數第二個
list1 = [5,8,9,34,214,54,22] list1.sort() #原地排序 ; sorted(list1) 非原地排序,list1不改變 print(list1[-2])?
思路3:
遍歷,聲明兩個變量,一個存最大的
一個存第二大的,然后逐一比對。
s = [1,2,3,4,5,-1,-2]max_num = s[0] second_max_num = s[0]for i in s:if i> max_num:second_max_num = max_nummax_num = iprint("第二大的元素是:",second_max_num)?
習題2:
python代碼得到2個列表的交集與差集
?
不許用set
交集思路:遍歷list1,判斷是否在list2中,在的話,則存入一個列表中。
差集思路:分別遍歷list1和2,如果不在對方的list中,則存入一個列表中
s1 = [1,2,3,9,10] s2=[2,3,9,11]result = []for i in s1:if i in s2:result.append(i)print("交集:",result)?
差集:
s1 = [1,2,3,9,10] s2 = [2,3,9,11]result = []for i in s1:if i not in s2:result.append(i) for i in s2:if i not in s1:result.append(i)print("差集:",result)?
差集2的實現方法: 2個集合的并集-交集=差集
s1 = [1,2,3,9,10] s2=[2,3,9,11]result1 = [] result2 = []for i in s1:if i in s2:result1.append(i) print("交集:",result1)s1=list(set(s1+s2)) for i in s1:if i not in result1:result2.append(i) print("差集:",result2)?
冒泡排序:
s = [-1,1,-2,2,3,-3]
?
第一步:交換2個元素
交換的方法1:
a,b = b,a
?
交換2:
temp=b
b=a
a=temp
?
第二步:我要找到這個list中最大的元素,把它放到列表的最后位置
位置0和位置1比,如果大,交換,否則不換
位置1和位置2位置比,如果大,交換,否則不換
位置2和位置3位置比,如果大,交換,否則不換
...
位置4和和位置5位置比,如果大,交換,否則不換
?
1)基于坐標做遍歷,最后一個元素不需要做遍歷動作
遍歷的反射:
?? 1 把元素逐一取出來
?? 2 基于坐標位置逐一取出來,i,i+1
s = [-1,1,-2,2,3,-3]for i in range(len(s)-1):if s[i] > s[i+1]:temp=s[i]s[i]=s[i+1]s[i+1]=temp print (s)2)使用if當前元素和后一個元素做比對,如果大了,交換,否則啥也不干
把最后1個元素我不處理了,把之前的所有數,在做相同工作,第二大
s = [-1,1,-2,2,3,-3]for i in range(len(s)-1-i):if s[i] > s[i+1]:temp=s[i]s[i]=s[i+1]s[i+1]=tempprint (s)?
把最后2個元素我不處理了,把之前的所有數,在做相同工作,第三大
把最后3個元素我不處理了,把之前的所有數,在做相同工作,第四大
.....
把最后n-1個元素我不處理了,把之前的所有數,在做相同工作,第n大
s = [-1,1,-2,2,3,-3]for j in range(len(s)-1):for i in range(len(s)-1-j):if s[i] > s[i+1]:temp=s[i]s[i]=s[i+1]s[i+1]=tempprint(s)dir(__builtins__) ?#查看內置的
help(round) ?#查看類或類似
?
不推薦使用關鍵字作為函數名,因為會覆蓋已有函數
函數:類外面的函數定義叫做函數
方法:類內部定義的函數叫做方法
?
求一個字符串中的字母個數函數
需判斷傳入參數的類型。
isinstance(s,str)
加個要求,必須使用ascii來判斷是否字母
def count_letter_num(s):if not isinstance(s,str):return Noneresult = 0for i in s:if (ord(i) >= ord("a") and ord(i) <= ord("z")) \or (ord(i) >= ord("A") and ord(i) <= ord("Z")):result +=1return resultprint("包含的字母數量:",count_letter_num("I am a boy!"))?
>>>?def?print_sth(s):
...?????"此函數用于打印"? #文檔字符串
...?????print(s)
...
>>>?print_sth("hi")
hi
>>>?print_sth.__doc__
'此函數用于打印'
>>>?help(print_sth)
Help?on?function?print_sth?in?module?__main__:
?
print_sth(s)
????此函數用于打印
?
>>>?import?os
>>>?os.getcwd()
'E:\\'
?
#時間戳?? 從1970-1-1 00:00
>>>?import?time
>>>?time.time()
1534649995.2979999
?
寫一個函數,這個函數要計算浮點數乘法的一萬次相乘后的時間耗時,浮
點數可以使用隨機小數
def count_float_compute_speed(n):import randomimport timestart_time = time.time()for i in range(n):result=random.random()**2end_time = time.time()return end_time-start_timeprint(count_float_compute_speed(10000000))?
不可變對象:所有的數字、字符串、元組
可變:set dict list 實例
參數傳不可變對象的時候,函數內外變量值是獨立的
參數傳可變對象的時候,函數內外變量值是關聯的
?
在函數內部,使用global變量,會對外部變量有影響。
a=100def compute():global aa+=1compute() print (a)#a改變了,是101
?
def add_end(L=[]):
L.append('END')
return L
print (add_end([1, 2, 3])) #調用正常
print (add_end(['x', 'y', 'z'])) #調用正常
print (add_end())#調用正常
print (add_end())#調用不正常
print (add_end())#調用不正常
?
修改成
def add_end(L=None):
??? if L is None:
??????? L =[]
??? L.append('END')
??? return L
?
print (add_end([1, 2, 3])) #調用正常
print (add_end(['x', 'y', 'z'])) #調用正常
print (add_end())#調用正常
print (add_end())#調用正常
print (add_end())#調用正常
?
?
默認參數值,將推薦值作為默認值
>>> def add(a,b=1,c=2):
...???? return a+b+c
...
>>> print(add(1,2,3))
6
>>> print(add(1,2))
5
>>> print(add(1))
4
?
>>>?"******abdc********".strip("*")
'abdc'
?
>>>?"******abdc********".lstrip("*")
'abdc********'
>>>?"******abdc********".rstrip("*")
'******abdc'
?
去除空白字符,包括 空格 /r /n /t 。
?
?
小練習:
add(a,b)
要求有個值是result來存結果
1 a,b 數字,相加
2 a,b 字符串,就當做字符串相加
3 a,b 如果list就當list相加
4?不滿足條件,則返回None
def add(a,b):if isinstance(a,(int,float)) and isinstance(b,(int,float)):result = a+belif isinstance(a,str) and isinstance(b,str):result = a+belif isinstance(a,list) and isinstance(b,list):result = a+belse:return Nonereturn resultprint(add(2,3)) print(add("a","b")) print(add([1,2],[3,4])) print(add("a",3)) print(add([1,2],3))?
?
?
命名參數
>>> def add(a,b,c):
...???? return a+b+c
...
>>> print(add(c=1,b=2,a=3))
6
>>> print(add(c=1,2,3))
? File "<stdin>", line 1
SyntaxError: positional argument follows keyword argu
?
命名參數必須放在非命名參數的后面
?
>>>?a,b?=?1,2
>>>?a
1
>>>?b
2
>>>?a,b?=?(1,2)
>>>?a
1
>>>?b
2
?
>>> def func(a,b):
...???? return a,b
...
func(1,2)? ->返回一個元組 (1,2)
?
正向代理:
客戶端和服務器之間的一個服務器或者是軟件,負責轉發用戶的
請求到源服務器。
發給不同的公司服務器
在你公司的局域網,某第三方服務器。
?
反向代理:
在被訪問服務器的局域網內,你的請求被它收到了之后,
會被反向代理服務器解析你的請求的url,然后將請求轉發
給不同的服務器處理。
?
反向代理+你要訪問的服務器是一組,是一個公司開發的。
外人不知道。
?
平臺,接口層:
10臺服務器,1萬用戶
1臺1-1000
2臺1001-2000
。。。。
10臺9000-10000
?
{ip:“13.2.3.3”,userid:"1"}
解析你的url--->轉發相應的服務器
Rewrite
?
練習:
輸入5個字母,聲明一個可變參數的函數,拼成一個單詞。
元組作為函數參數
def word(*arg):result=""for i in arg:result += ireturn resultprint(word("h","e","l","l","o")) print(word("h","eddd","le","l2","o3"))?
字典作為函數參數
def add(**kw):print(type(kw))for i in kw:print(i)for j in kw.values():print(j)print(add(a="1",b=2,c=3))?
題目:使用必填參數、默認參數、可變元組參數、可變字典參數計算一下單詞的長度之和。
?
def count_letter_num(a,b="abc",*arg,**kw):result = 0result += len(a)result += len(b)print(arg)print(kw)for i in arg:result+=len(i)for i in kw.values():result+=len(i)return result?
#"a"賦值給參數a了,"b"給參數b了,cde給arg,x和y給kw做key
#f和g作為kw的value
print(count_letter_num("a","b","c","d","e",x="f",y="g"))
print(count_letter_num("a"))
print(count_letter_num("a",c="x"))
?
lambda函數
?
?
六劍客解決一行代碼:
Lambda
切片
Map
Filter
Reduce
推倒列表
?
Repr方法
>>>?s=repr([1,2,3])
>>>?eval(s)
[1,?2,?3]
>>>?s=repr((1,2,3))
>>>?eval(s)
(1,?2,?3)
?
?
>>> class P():
...???? def __str__(self):
...???????? return "hi"
...???? def __repr__(self):
...???????? return "ggggg"
...
>>> p=P()
>>> p
ggggg
>>> str(p)
'hi'
?
>>> type(1)
<class 'int'>
>>> type(1.1)
<class 'float'>
>>> type(1+1j)
<class 'complex'>
>>> type("a")
<class 'str'>
>>> type([1])
<class 'list'>
>>> type((1,2))
<class 'tuple'>
>>> type({1:1})
<class 'dict'>
>>> type(set([1]))?? #集合
<class 'set'>
>>>?type({1,2})
<class?'set'>
>>>
?
Map
大寫變小寫
list(map(lambda x:x+1,[1,2,3]))
list(map(lambda x:chr(ord(x)+32),["A","B","C"]))
list(map(lambda x:x.lower(),["A","B","C"]))
?
>>>?def?l(s):return?s.lower()
...
>>>?list(map(l,"ABCabc"))
['a',?'b',?'c',?'a',?'b',?'c']
?
Filter
#過濾偶數
>>>?def?f(n):
...?????if?n?%?2?==0:
...?????????return?n
...
?
>>>?list(filter(f,[1,2,3,4]))
[2,?4]
?
#過濾小寫字母
>>> def f(n):
...???? if n >="a" and n <="z":
...???????? return n
...
>>> list(filter(f,"AAaaBBbb"))
['a', 'a', 'b', 'b']
?
Reduce:
from functools import reduce
>>> reduce(lambda x,y:x+y,[1,2,3,4])
10
?
第一次計算:x=1,y=2
第二次計算:x=3,y =3
第三次計算:x=6,y=4
6+4=10
?
遞歸
1)? 調用自己
2)? 有結束的判斷
?
累加:1+2+3+4+5
result?=0
for?i?in?range(1,6):
????result?+=i
?
def?add(n):
????
????if?n?==1:
????????return?1
????return?add(n-1)+n
?
?
n=3:第一次調用:add(3-1)+3--->add(2)+3=3+3=6
n=2:第二次調用:add(2-1)+2--->add(1)+2=1+2=3
n=1:第三次調用:add(1)--->return?1
?
轉載于:https://www.cnblogs.com/xuefeifei/p/9504830.html
總結
以上是生活随笔為你收集整理的第6次全天课笔记-20180819的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python直接赋值,浅拷贝和深度拷贝
- 下一篇: st什么意思