python基礎篇
注:適合萌新學習python并且里面的內容會持續的更新!
說明:并非是最優代碼,但程式完全正確!因為此時作者也處在學習階段!
關于for回圈
例題:創建一個資料集,包含1到10的隨機整數,共計100個數,并統計每個數出現的次數,
// 方法1
import random //引入random模塊
lst = [] //定義一個空串列
d = dict() //定義一個空字典
for i in range(100): //回圈100次
n = random.randint(1,10) //每回圈一次隨機拿到1——10以內的任意一個數
if n in d :
d[n] + = 1 //如果這個數作為鍵在字典里,值加1
else:
d[n] = 1 //否則值等于1
print(d)
//方法2
import random
lst = []
for i in range(100):
n = random.randint(1,10)
lst.append(n)
d={}
for n in lst:
if n in d:
d[n] + = 1
else:
d[n] = 1
常用于for回圈的函式
1. range()
2. zip()
3. enumerate( )
4. 串列決議
例題:求100以內能被三整除的數
lst = []
for i in range(100):
if i % 3 == 0;
lst.append(i)
print(lst)
用range方法實作兩個串列的對應值相加
c = [1,2,3,4,5]
d = [6,7,8,9,1]
r = []
for i in range(len(c))://把串列中的每一個元素所對應的索引拿出來了
r.append(c[i] + d[i])
用zip方法實作兩個串列的對應值相加
c = [1,2,3,4,5]
d = [6,7,8,9,1]
r = []
for x,y in zip(c,d):
r.append(x+y)
print(r)
enumerate()方法:列舉 回傳索引值
>>>s = ['one','two','three']
>>>list(enumerate(s))
[(0, 'one'), (1, 'two'), (2, 'three')]//得到索引和值
串列決議
用途:定義一個空串列,向空串列中追加一些符合條件的元素時使用串列決議
用串列決議法求100以內能被三整除的數
>>>[i for i in range(100) if i % 3 == 0]
結果是:[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
>>>range(0, 100, 3)
>>>list(range(0, 100, 3))
例題 :字串s=‘life is short You need python’,統計這個字串中每個字母出現的次數,
s = 'life is short You need python'
lst = [] //定義一個空串列
d = dict() //定義一個空字典
for i in s: //回圈獲取s中的每個字母
if i.isalpha(): //判斷回圈得到的是否是一個字符,是字符則執行后面的代碼塊 否則回傳false
if i in d :
d[i] + = 1 //'鍵'放在字典里并且'值'加1
else:
d[i] = 1
print(d)
關于while回圈
格式: while[condition]:
statements
a = 0
while a < 3:
s = input("input your lang:")
if s == 'python':
print("your lang is {0}".format(s))
break //當代碼執行到這里時,會跳出當前回圈(此處跳出while 執行print("the end a:",a))
else:
a+=1
print("a=",a)
print("the end a:",a)
a=11
while a > 0:
a-=1;
if a % 2 == 0:
continue
print(a)
else:
print(a)
用while回圈做一個小游戲:
制作一個滿足如下功能的猜數游戲:
1.計算機隨機生成一個100以內的正整數;
2.用戶通過鍵盤輸入數字,猜測計算機所生成的亂數,
注意:對用戶的輸入次數不做限制,
import random
computer_name = random.randint(1,100) #表示從1——100以內隨機取一個數
while True: #表示一直回圈,直到遇到結束標志
user_name = input("請輸入你要猜測的數字:") #獲得的是字串型別
if not user_name.isdigit():
print("請輸入1——100以內的整數" )
elif int(user_name) <0 or int(user_name) >= 100:
print("請輸入1——100以內的整數")
else:
if int(user_name)==computer_name:
print("you are win")
break
elif int(user_name)<computer_name:
print("you are smaller")
else :
print("you are bigger")
函式和裝飾器
函式的定義:def wrr(x,y,z):【def;函式名稱;引數串列】
(此處縮進四個空格)do something return object【函式內陳述句塊】
函式結束 回傳值 return
例子:
def add(x,y):
r = x +y
return r
c = add(2,3)
print("c的值為:",c)
結果為:c=5
引數收集
一個 ‘*’ 的作用
def fun(x,*args):
print("x=",x)
print("args=",args)
fun(1,2,3,4,5,6)
結果為:
x= 1
args= (2, 3, 4, 5, 6)
二個 ‘*’ 的作用
def bar(x,**kwargs):
print("x=",x)
print("args=",kwargs)
bar(1,a=2,b=3,c=4)
結果為:
x= 1
args= {'a': 2, 'b': 3, 'c': 4}
引數收集的擴展:
def foo(*args,**kwargs):
print("x=",args)
print("args=",kwargs)
foo(1,2,3,a=9,b=7,c=6)
結果為:
x= (1, 2, 3)
args= {'a': 9, 'b': 7, 'c': 6}
函式的嵌套
例子:
def book(name):
return "the name of my book is{0}".format(name)
def p_deco(func): #函式的嵌套
def wrapper(name):
return "<p>{0}<p>".format(func(name))
return wrapper
wrr = p_deco(book)
py_book = wrr(" python 學習")
print(py_book)
結果是:
<p>the name of my book is python 學習<p>
裝飾器
def p_deco(func): #函式的嵌套
def wrapper(name):
return "<p>{0}<p>".format(func(name))
return wrapper
def div_deco(func): #用到了函式的嵌套
def wrapper(name):
return "<div>{0}<div>".format(func(name))
return wrapper
@div_deco #裝飾器
@p_deco #裝飾器
def book(name): #p_deco(func)裝飾了book(name)函式
return "the name of my book is{0}".format(name)
#此程式裝飾器的功能就是下面注釋的兩行
#whr = p_deco(book)
#py_book =whr(" python 學習")
py_book=book(" python 學習")
print(py_book)
結果是:
<div><p>the name of my book is python 學習<p><div>
練習
撰寫一個測驗函式執行時間的裝飾器函式
import time
def timing_func(func):#撰寫裝飾器函式
def wrapper():
start = time.time()#記錄開始時間
func() #執行這個函式
stop = time.time()#記錄結束時間
return stop-start
return wrapper
@timing_func #裝飾器
def test_list_append():
lst=[]
for i in range(1000000): #運用for回圈取值
lst.append(i)#把每個數追加到串列中
@timing_func #裝飾器
def test_list_compre():
[i for i in range(1000000)] #運用串列決議 取值
a=test_list_append()
b=test_list_compre()
print("運行test_list_append方法所運行的時間",a)
print("運行test_list_compre方法所運行的時間",b)
執行結果如下:
運行test_list_append方法所運行的時間 0.12466740608215332
運行test_list_compre方法所運行的時間 0.08578181266784668
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/128717.html
標籤:其他
上一篇:PTA 線性表 7-1 約瑟夫環(Josephus)問題(by Yan) (100分) 按出列次序輸出每個人的編號
下一篇:二叉樹左平衡旋轉疑問
