文章目錄
1.函數
1.1 函數的定義和調用
定義函數的關鍵字:def
def 函數名稱(參數)
注意:函數只有通過函數名調用的時候纔會運行函數中的內容,否則運行爲空
示例:定義求和函數
def add():##定義求和函數
num1 = 20
num2 = 30
result = num1 + num2
print('%d + %d = %d' %(num1,num2,result))
add()##調用求和函數
1.2 嵌套函數的定義和調用
def hello():
print('hello')
def python():
print('python')
python()##嵌套函數的定義和調用需要寫在調用函數內部
hello()
2.函數+變量
def 函數名稱(形參)
注意:形參的內容取決於實參的內容
def year(a):##定義函數(a爲形參)
print('hello',a)
year('2019')##調用函數(2019爲實參)
year('2020')##形參的內容取決於實參的內容
3.四種形參
參數分爲形參和實參。
形參分爲:位置參數 、默認參數 、可變參數 、關鍵字參數
3.1 位置參數
要求:實參和位置參數的參數個數保持一致,且順序保持一致
def Info(name,age):
print(name,age)
Info('sam',11)###位置參數和實參順序需要一致
Info(11,'sam')
Info(age=11,name='sam')##標記key值位置可以不一樣
3.2 默認參數
形參和實參個數可以不一樣
def mypow(x,y=2):##y=2爲默認參數
print(x**y)
mypow(4)
mypow(2,3)
3.3 可變參數
def mysum(*a):##* 表示可以接受多個參數
sum = 0
for item in a:
sum += item
print(sum)
mysum(1,2,3,4,5)
3.4 關鍵字參數
注意:kwargs爲關鍵字參數,是一個字典,可以傳任意多個鍵值對
def getInfo(name,age,**kwargs):##**kwargs關鍵字參數,是一個字典
print(name,age)
print(kwargs)
getInfo('linda',18,gender='female',hobbies=['coding','running'])
4.函數的返回值
注意:返回值的關鍵字爲:return,如果有返回返回值,沒有返回none
def mypow(x,y=2):
return x ** y, x + y
a,b = mypow(3)
print(a,b)
5.函數的變量作用域
局部變量: 在函數內部定義的變量,只在函數內部起作用,函數執行結束,變量會自動刪除
全局變量: 會始終生效
a = 1##全局變量
print('outside:',id(a)) ####id(a)變量在內存中存儲的位置
def fun():
a = 5##局部變量
print('inside:',id(a))
fun()
print(a)
print(id(a))
a = 1
print('outside:',id(a))
def fun():
global a##聲明爲全局變量
a = 5
print('inside:',id(a))
fun()
print(a)
print(id(a))
6.函數的生成式
6.1 列表生成式
[expression for i in seq if...]
示例:
轉換成生成式:
s = '3 25 99'
k,a,b = [int(item) for item in s.split()]
print(k,a,b)
練習:求平方和
普通方法
列表生成式方法
print([item ** 2 for item in range(1,11)])
練習:求偶數的平方和
普通方法
列表生成式方法
print([item ** 2 for item in range(2,11,2)])
也可以繼續加條件:
print([item ** 2 for item in range(1,11) if item %2 == 0])
練習:求所有質數
普通方法
列表生成式方法
def isPrime(num):
for i in range(2,num):
if num % i == 0:
return False
else:
return True
print([i for i in range(2,101) if isPrime(i)])
6.2 字典生成式
1.示例
假設有20個學生,學生名爲westosX,學生分數在60~100之間,篩選出成績在90分以上得學生
方案一:
import random
stuInfo = {}
for i in range(20):
name = 'student'+str(i)
score = random.randint(60,100)
stuInfo[name] = score
print(stuInfo)
highscore = {}
for name,score in stuInfo.items():
if score > 90:
highscore[name] = score
print(highscore)
方案二:(字典生成式)
import random
stuInfo = {}
for i in range(20):
name = 'student'+str(i)
score = random.randint(60,100)
stuInfo[name] = score
print({name:score for name,score in stuInfo.items() if score >90})
2.所有的key值變大寫
d = dict(a=1,b=2)
方案一:
d = dict(a=1,b=2)
print(d)
new_d = {}
for i in d:
new_d[i.upper()] = d[i]
print(new_d)
方案二:(字典生成式)
d = dict(a=1,b=2)
print(d)
print({k.upper():v for k,v in d.items()})
3.大小寫key值合併,統一以小寫輸出
d = dict(a=2, b=1, c=2, B=9, A=10)
輸出{'a': 12, 'b': 10, 'c': 2}
方案一:
d = dict(a=2, b=1, c=2, B=9, A=10)
new_d = {}
for k,v in d.items():
low_k = k.lower()
if low_k not in new_d:
new_d[low_k] = v
else:
new_d[low_k] += v
print(new_d)
方案二:(字典生成式)
d = dict(a=2, b=1, c=2, B=9, A=10)
print({k.lower():d.get(k.lower(),0) + d.get(k.upper(),0) for k in d})
7.高階函數
7.1 定義
1.函數本身可以作爲變量,給變量賦值
def fun(a,b):
return a+b
a = fun(1,2)
print(a)
2.變量也可以指向函數
f = abs
print(f(-10))
3.函數也可作參數
def fun(x,y,f):
return f(x),f(y)
print(fun(-10,34,abs))
8.內置高階函數
8.1 map()函數
1.map函數的參數
map()函數接收兩個參數,一個是函數,一個是序列
map將傳入的函數依次作用到序列的每個元素,並且把結果作爲新的序列返回
2.map函數求階乘
生成10個[2,7]之間的隨機數求階乘
import random
def f(x):
res = 1
for i in range(1,x+1):
res *= i
return res
li = [random.randint(2,7) for i in range(10)]
print(li)
print(list(map(f,li)))
8.2 reduce累計函數
reduce:把一個函數作用在一個序列上,這個函數必須接收兩個參數,reduce把結果繼續和序列的下一個元素做累積計算
如:
reduce( f , [x1,x2,x3,x4,x5] ) = f( f( f(x1,x2) , x3) ,x4)
注意:
python2:reduce是內置函數
python3:from functools import reduce
1.累乘
from functools import reduce
def multi(x,y):
return x * y
print (reduce(multi,range(1,4)))
2.累加
from functools import reduce
def add(x,y):
return x + y
print (reduce(add,[1,2,3,4,5]))
8.3 filter過濾函數
filter過濾函數和map()類似,也接收一個函數和一個序列
但是和map()不同的是,filter()把傳入的函數依次作用於每個元素,然後根據返回值是True還是False決定保留還是丟棄該元素
練習:判斷是否爲偶數
def isodd(num):
if num % 2 == 0:
return True
else:
return False
print(list(filter(isodd,range(100))))
8.4 sorted排序函數
1. .sort()方法
li = [2,1,3,4]
li.sort()
print(li)
2. sorted函數
li = [48,9,6,7]
print(sorted(li,reverse=True))
3.指定排序方式
info = [
# 商品名稱 商品數量 商品價格
('apple1',200,32),
('apple2',40,12),
('apple3',40,2),
('apple4',1000,23),
('apple5',40,5)
]
print(sorted(info))
def sorted_by_count(x):
return x[1]
print(sorted(info,key=sorted_by_count))
def sorted_by_price(x):
return x[2]
print(sorted(info,key=sorted_by_price))
def sorted_by_count_price(x):
return x[1],x[2]
print(sorted(info,key=sorted_by_count_price))
4.排序練習(移動0)
給定一個整形數組, 將數組中所有的0移動到末尾, 非0項保持不變;
在原始數組上進行移動操作, 勿創建新的數組;
輸入:第一行是數組長度, 後續每一行是數組的一條記錄
4
0
7
0
2
輸出:調整後數組的內容
4
7
2
0
0
n = ''.join(input().split())
li = (int(i) for i in n)
def move_zero(item):
if item == 0:
return 2
else:
return 1
print(sorted(li,key=move_zero))
9.匿名函數
匿名函數的關鍵字爲lambda,冒號前是形參,冒號後是返回值
print(lambda *args, **kwargs: (args, kwargs))
9.1 reduce+lambda
from functools import reduce
def add(x,y):
return x+y
print(reduce((lambda x,y:x+y),[1,2,3,4,5]))
9.2 map+lambda
def mypow(x):
return x ** 2
print(list(map(lambda x:x**2,range(6))))
9.3 fileter+lambda
print(list(filter(lambda x:x % 2 ==0,range(100))))
9.4 lambda移動數組中的0
nums = [0, 7, 0, 1, 2, 1, 5,1, 7, 8, 0, 67, 1, 3, 4]
nums = [0, 7, 0, 1, 2, 1, 5,1, 7, 8, 0, 67, 1, 3, 4]
print(sorted(nums,key=lambda x:1 if x==0 else 0))
10.函數的練習
練習:編寫函數, 可以接收任意多個數並返回元組.
編寫一個函數caculate, 可以接收任意多個數,返回的是一個元組.
元組的第一個值爲所有參數的平均值, 第二個值是大於平均值的所有數.
def caculate(*args):##可變參數可以接收任意多個數
avg = sum(args) / len(args)
up_avg = []##定義空列表
for item in args:
if item > avg:
up_avg.append(item)
return avg,up_avg 返回
a = caculate(1,2,3,4,5,6,7)
print(a)
練習:編寫一個函數, 接收字符串參數, 返回一個元組(大小寫字母個數)
編寫一個函數, 接收字符串參數, 返回一個元組,'ehllo WROLD
元組的第一個值爲大寫字母的個數, 第二個值爲小寫字母個數.
def fun(x):
upper_count = 0
lower_count = 0
for i in x:
if i.isupper():
upper_count += 1
elif i.islower():
lower_count += 1
else:
continue
return upper_count,lower_count
a = fun('ehllo WROLD')
print(a)
練習: 編寫函數,返回列表,使下標前後逆序
編寫函數, 接收一個列表(包含30個1~100之間的隨機整形數)和一個整形
數k, 返回一個新列表.
函數需求:
- 將列表下標k之前對應(bu包含k)的元素逆序;
- 將下標k及之後的元素逆序;
[1,2,3,4,5] 2 [2,1,5,4,3]
def fun(li,k):
if k < 0 or k > len(li):
return 'error k'
return li[:k][::-1] + li[k:][::-1]
print(fun([1,2,3,4,5],2))
練習:模擬輪盤抽獎遊戲
輪盤分爲三部分: 一等獎, 二等獎和三等獎;輪盤轉的時候是隨機的,
如果範圍在[0,0.08)之間,代表一等獎,
如果範圍在[0.08,0.3)之間,代表2等獎,
如果範圍在[0.3, 1.0)之間,代表3等獎,
模擬本次活動1000人蔘加, 模擬遊戲時需要準備各等級獎品的個數.
import random
reword_dict = {
'一等獎':(0,0.08),
'二等獎':(0.08,0.3),
'三等獎':(0.3,1)
}
def userfun():
num = random.random()
for k,v in reword_dict.items():
if v[0] <= num < v[1]:
return k
resultDict = {}
for i in range(1000):
res = userfun()
if res not in resultDict:
resultDict[res] = 1
else:
resultDict[res] += 1
for k,v in resultDict.items():
print(k,'--->',v)
練習:計算有多少個正整數n滿足a<=n<=b,且k*f(n)=n
題目需求:
對於一個十進制的正整數, 定義f(n)爲其各位數字的平方和,如:
f(13) = 1**2 + 3**2 = 10
f(207) = 2**2 + 0**2 + 7**2 = 53
下面給出三個正整數k,a, b,你需要計算有多少個正整數n滿足a<=n<=b,且k*f(n)=n
輸入: 第一行包含3個正整數k,a, b, k>=1, a,b<=10**18, a<=b;
輸出:輸出對應的答案;
示例:
輸入: 51 5000 10000
輸出: 3
def f(n):
n = str(n)
sum = 0
for item in n:
sum += int(item) ** 2
return sum
s = input()
li = []
for item in s.split():
li.append(int(item))
k,a,b = li
count = 0
for i in range(a,b+1):
if k * f(i) == i:
print(i)
count += 1
print(count)
練習:編寫程序計算有多少對質數的和等於輸入的正整數
- 題目描述:
給定一個正整數,編寫程序計算有多少對質數的和等於輸入的這個正整數,並輸出結果,輸入值小於1000。如:輸入爲10, 程序應該輸出結果爲2。(共有兩對質數的和爲10,分別爲(5,5),(3,7), [2,3,5,7]) - 輸入描述:輸入包括一個整數n,(3 ≤ n < 1000)
- 輸出描述:輸出對數
num = int(input())
def isPrime(num):
for i in range(2,num):
if num % i == 0:
return False
else:
return True
primeli = [i for i in range(2,num) if isPrime(i)]
primecount = 0
for item in primeli:
if (num - item) in primeli and item <= num -item:
primecount += 1
print(primecount)