python入門(五)

來源:互聯網
上載者:User

標籤:sort   join   etc   byte   路徑   python入門   into   get   必須   

一.函數傳回值

 1.函數如果返回多個值,他會把這幾個值放到一個元組裡面
 2.也可以用多個變數來接收

返回多個值放到元組裡面 def say():     num1=1     num2=2     num3=3     return num1,num2,num3 res = say() print(res)
多個變數接收
res1,res2,res3 = say()
print(res1)
print(res2)
print(res3)

二.匿名函數

匿名函數,這個函數功能很簡單,只用一次

lambdares = lambda x:x+1#冒號後面的是函數體,也是函數的處理邏輯,冒號前面的傳回值print(res(1))

三.清單產生器

import randomred_num= random.sample(range(1,34),6)#外面是小括弧的話,他就不是一個list了,他是一個產生器# 產生器比list要節約記憶體,他是每次迴圈的時候,會根據規則計算一個元素,放到記憶體裡面。# list他是把所有的元素都放在記憶體裡面。l  = [i for i in  range(1,101,2)]#產生100以內的奇數new_num = [str(num).zfill(2)for num in red_num] #列表產生式print(new_num)print(l)#產生器例子l  = (i for i in  range(1,101,2))for l2 in l:    print(l2)print(l.__next__)#表示每次列印一個值# #下面的這一串與上面的【列表產生式】的作用一樣for num in red_num:    temp = str(num).zfill(2)    new_num.append(temp)print(new_num)# #練習一(列表產生式)a = 5b = 4if a>b:    c= aelse:    c= bc = a if a>b else b #三元運算式

四.字典排序

d = {‘a‘:4,‘c‘:2,‘b‘:3}#字典是無序,直接對字典排序是不存在的print(d.items())print(sorted(d.items()))#sorted幫我們迴圈調用產生了一個二維數組,預設是按照key排序的res=sorted(d.items(),key=lambda x:x[0])#根據key排序res1=sorted(d.items(),key=lambda x:x[1])#根據value排序print(res)print(res1)for k,v in res:#迴圈二維數組    print(k,v)l =[    [1,2,3,4],    [1,2,4,3]]for a,b,c,d in l:    print(a,b,c,d)def my(name:str):    print(name)my([‘123‘,‘456‘])

五.os常用模組

# os模組常用方法:os.listdir("d:\\")#列出目錄下所有的檔案夾和檔案os.remove()#刪除檔案os.rename(ols,new)#重新命名print(os.sep)#當前作業系統的路徑分隔字元print(os.path.dirname("e:\\syz\\lpy-code"))#擷取父目錄,擷取上一級目錄print(os.path.exists("/user/local"))#目錄/檔案是否存在print(os.path.isfile("lpy.py"))#判斷檔案是否存在,判斷是不是檔案print(os.path.isdir("e:\\syz"))#是否是一個路徑,目錄是否存在size = os.path.getsize(‘x.py‘)#擷取檔案的大小res = os.system(‘ipconfig‘)#執行作業系統命令,但擷取不到結果res = os.popen(‘ipconfig‘).read()#可以擷取到命令執行的結果print(os.path.abspath(__file__))#擷取絕對路徑print(os.path.dirname("e:\\syz\\lpy-code"))#擷取父目錄,擷取上一級目錄print(os.path.isfile("lpy.py"))#判斷檔案是否存在,判斷是不是檔案print(os.path.isdir("e:\\syz"))#是否是一個路徑,目錄是否存在size = os.path.getsize(‘x.py‘)#擷取檔案的大小# 可用於限制上傳檔案大小print(os.path.join("root",‘hehhe‘,‘a.sql‘))#拼接成一個路徑for abs_path,dir,file in os.walk(‘E:\syz\syz-code\day6‘):    print(abs_path,dir,file)# abs_path當前迴圈的絕對路徑# dir目錄下所有的檔案夾[ ]# file目錄下所有的檔案[]

六.匯入模組的順序與方法

python匯入模組時的順序:
1.從目前的目錄下找需要匯入的python檔案,第一順序
2.從python的環境變數中找 sys.path,第二順序
匯入模組的實質:
就是把匯入的這個python檔案從頭到尾執行一遍
#方法一:import lpyprint(lpy.name)lpy.my()#方法二:from lpy import  my,namemy()print(name)# 方法三:from lpy import *   #所有的,最好不用這個方法,可能匯入多個模組不好判斷後面調用的函數屬於哪個模組my()print(name)

七.sys模組

import  sysprint(sys.platform)#判斷作業系統print(sys.path)#python的環境變數sys.path.append(‘../day5‘)#匯入 其他目錄下的模組,要先把目錄加入環境變數print(sys.path)import  zuoyesys.path.insert(0,word,‘E:\syz\syz-code\day5‘)print(sys,path)
print(sys.argv)#用來擷取命令裡面運行python檔案的時候傳入的參數,它是一個list,這個list預設就有一個參數,就是當前的檔案名稱

  

八.時間模組

1.時間戳記:從unix元年到現在過了多少秒
2格式化好的時間
# 先轉成時間元組import timeprint(time.time())#擷取目前時間戳# time.sleep(10)today = time.strftime(‘%Y-%m-%d %H:%M:%S‘)print(today)print(time.gmtime())#預設取的是標準時區的時間s = print(time.localtime(1514198608))#取的是當前時區的時間print(time.strftime(‘%Y-%m-%d %H:%M:%S‘,s))# 時間戳記轉換時間元組# 1.時間戳記轉成時間元組 time.localtime()# 2.再把時間元組轉成格式化的時間def timestamp_to_fomat(timestamp=None,format=‘%Y-%m-%d %H:%M:%S‘):    # 1.預設返回當前格式化好的時間    # 2.傳入時間戳記的話,把時間戳記轉化成格式化好的時間,返回    if timestamp:        time_tuple= time.localtime(timestamp)        res = time.strftime(format,time_tuple)    else:        res = time.strftime(format)#預設取目前時間    return  res2018-4-21tp = time.strptime(‘2018-4-21‘,‘%Y-%m-%d‘)#把格式化好的時間轉成時間元組的print(time.mktime(tp))#把時間元組轉成時間戳記def strToTimestamp(str=None,format=‘%Y%m%d%H%M%S‘):    #20180421165643    #預設返回目前時間戳    if str:        tp = time.strptime(str,format)#轉成時間元組        res = time.mktime(tp)#再轉成時間戳記    else:        res = time.time()#預設取當前是按戳    return int(res)print(strToTimestamp())print(strToTimestamp(‘20181129183859‘))import datetimeprint(datetime.datetime.today())#擷取目前時間精確到秒print(datetime.date.today())#精確到天res = datetime.date.today()+datetime.timedelta(days=5)#擷取到5天后,-5五天前res = datetime.date.today()+datetime.timedelta(minutes=5)#擷取到5分鐘後,-5五天前print(res)

九.加密模組

import hashlib# 字串不能直接加密m = hashlib.md5()passwd = ‘123‘passwd.encode()#把字串專車個bytes類型m.update(passwd.encode())#不能直接對字串加密,要先把字串轉成bytes類型print(m.hexdigest())def my_md5(str):    new_str = str.encode()#把字串轉成bytes類型    m = hashlib.md5()#執行個體化md5對象    m.update(new_str)#加密    areturn m.hexdigest()#擷取結果返回m = hashlib.sha256()m.update(passwd.encode())

十.操作mysql

# 1.串連上資料庫 帳號,密碼,IP,連接埠號碼,資料庫# 2.建立遊標# 3.執行sql# 4.擷取結果# 5.關閉遊標# 6.串連關閉import pymysqlcoon = pymysql.connect(    host=‘118.24.3.40‘,user=‘jxz‘,passwd=‘123456‘,    port=3306,db=‘jxz‘,charset=‘utf8‘    #port必須寫成int類型    #charset這裡必須寫成utf8)cur = coon.cursor()# cur.execute(‘select * from stu;‘)cur.execute(‘insert into stu (id,name,sex) VALUE (1,"koukou","女");‘)# delete update insert 必須commitcoon.commit()res = cur.fetchall()print(res)cur.close()coon.close()

十一.excel模組

import xlwtbook = xlwt.Workbook()#建立一個excelsheet = book.add_sheet(‘sheet1‘)#加sheet頁sheet.write(0,0,‘姓名‘)#行,列,要寫入的內容sheet.write(0,0,‘年齡‘)sheet.write(0,0,‘性別‘)book.save(‘stu.xls‘)

 

  

  

  

python入門(五)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.