a一级爱做片免费观看欧美,久久国产一区二区,日本一二三区免费,久草视频手机在线观看

新聞中心

EEPW首頁 > 消費電子 > 設計應用 > Python編程中常用的12種基礎知識

Python編程中常用的12種基礎知識

作者: 時間:2018-07-25 來源:網絡 收藏

Python 編程中常用的12 種基礎知識總結:正則表達式替換,遍歷目錄方法,列表按列排序、去重,字典排序,字典、列表、字符串互轉,時間對象操作,命令行參數解析(getopt),print 格式化輸出,進制轉換,python 調用系統命令或者腳本,Python 讀寫文件。

本文引用地址:http://www.j9360.com/article/201807/383748.htm

1、正則表達式替換

目標: 將字符串 line 中的 overview.gif 替換成其他字符串

注意: 其中 1 是匹配到的數據,可以通過這樣的方式直接引用

2、遍歷目錄方法

在某些時候,我們需要遍歷某個目錄找出特定的文件列表,可以通過os.walk方法來遍歷,非常方便

import os

fileList = []

rootdir = /data

for root, subFolders, files in os.walk(rootdir):

if '.svn' in subFolders: subFolders.remove('.svn') # 排除特定目錄

for file in files:

if file.find(.t2t) != -1:# 查找特定擴展名的文件

file_dir_path = os.path.join(root,file)

fileList.append(file_dir_path)

print fileList

3、列表按列排序(list sort)

如果列表的每個元素都是一個元組(tuple),我們要根據元組的某列來排序的化,可參考如下方法

下面例子我們是根據元組的第2列和第3列數據來排序的,而且是倒序(reverse=True)

>>> a = [('2011-03-17', '2.26', 6429600, '0.0'), ('2011-03-16', '2.26', 12036900, '-3.0'),

('2011-03-15', '2.33', 15615500,'-19.1')]

>>> print a[0][0]

2011-03-17

>>> b = sorted(a, key=lambda result: result[1],reverse=True)

>>> print b

[('2011-03-15', '2.33', 15615500, '-19.1'), ('2011-03-17', '2.26', 6429600, '0.0'),

('2011-03-16', '2.26', 12036900, '-3.0')]

>>> c = sorted(a, key=lambda result: result[2],reverse=True)

>>> print c

[('2011-03-15', '2.33', 15615500, '-19.1'), ('2011-03-16', '2.26', 12036900, '-3.0'),

('2011-03-17', '2.26', 6429600, '0.0')]

4、列表去重(list uniq)

有時候需要將list中重復的元素刪除,就要使用如下方法

>>> lst= [(1,'sss'),(2,'fsdf'),(1,'sss'),(3,'fd')]

>>> set(lst)

set([(2, 'fsdf'), (3, 'fd'), (1, 'sss')])

>>>

>>> lst = [1, 1, 3, 4, 4, 5, 6, 7, 6]

>>> set(lst)

set([1, 3, 4, 5, 6, 7])

5、字典排序(dict sort)

一般來說,我們都是根據字典的key來進行排序,但是我們如果想根據字典的value值來排序,就使用如下方法

>>> from operator import itemgetter

>>> aa = {a:1,sss:2,ffdf:'5',ffff2:'3'}

>>> sort_aa = sorted(aa.items(),key=itemgetter(1))

>>> sort_aa

[('a', '1'), ('sss', '2'), ('ffff2', '3'), ('ffdf', '5')]

從上面的運行結果看到,按照字典的value值進行排序的

6、字典,列表,字符串互轉

以下是生成數據庫連接字符串,從字典轉換到字符串

>>> params = {server:mpilgrim, database:master, uid:sa, pwd:secret}

>>> [%s=%s % (k, v) for k, v in params.items()]

['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']

>>> ;.join([%s=%s % (k, v) for k, v in params.items()])

'server=mpilgrim;uid=sa;database=master;pwd=secret'

下面的例子 是將字符串轉化為字典

>>> a = 'server=mpilgrim;uid=sa;database=master;pwd=secret'

>>> aa = {}

>>> for i in a.split(';'):aa[i.split('=',1)[0]] = i.split('=',1)[1]

...

>>> aa

{'pwd': 'secret', 'database': 'master', 'uid': 'sa', 'server': 'mpilgrim'}

7、時間對象操作

將時間對象轉換成字符串

>>> import datetime

>>> datetime.datetime.now().strftime(%Y-%m-%d %H:%M)

'2011-01-20 14:05'

時間大小比較

>>> import time

>>> t1 = time.strptime('2011-01-20 14:05',%Y-%m-%d %H:%M)

>>> t2 = time.strptime('2011-01-20 16:05',%Y-%m-%d %H:%M)

>>> t1 > t2

False

>>> t1 t2

True

時間差值計算,計算8小時前的時間

>>> datetime.datetime.now().strftime(%Y-%m-%d %H:%M)

'2011-01-20 15:02'

>>> (datetime.datetime.now() - datetime.timedelta(hours=8)).strftime(%Y-%m-%d %H:%M)

'2011-01-20 07:03'

將字符串轉換成時間對象

>>> endtime=datetime.datetime.strptime('20100701',%Y%m%d)

>>> type(endtime)

>>> print endtime

2010-07-01 00:00:00

將從 1970-01-01 00:00:00 UTC 到現在的秒數,格式化輸出

>>> import time

>>> a = 1302153828

>>> time.strftime(%Y-%m-%d %H:%M:%S,time.localtime(a))

'2011-04-07 13:23:48'

8、命令行參數解析(getopt)

通常在編寫一些日運維腳本時,需要根據不同的條件,輸入不同的命令行選項來實現不同的功能 在Python中提供了getopt模塊很好的實現了命令行參數的解析,下面距離說明。請看如下程序:

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import sys,os,getopt

def usage():

print '''''

Usage: analyse_stock.py [options...]

Options:

-e : Exchange Name

-c : User-Defined Category Name

-f : Read stock info from file and save to db

-d : delete from db by stock code

-n : stock name

-s : stock code

-h : this help info

test.py -s haha -n HA Ha

'''

try:

opts, args = getopt.getopt(sys.argv[1:],'he:c:f:d:n:s:')

except getopt.GetoptError:

usage()

sys.exit()

if len(opts) == 0:

usage()

sys.exit()

for opt, arg in opts:

if opt in ('-h', '--help'):

usage()

sys.exit()

elif opt == '-d':

print del stock %s % arg

elif opt == '-f':

print read file %s % arg

elif opt == '-c':

print user-defined %s % arg

elif opt == '-e':

print Exchange Name %s % arg

elif opt == '-s':

print Stock code %s % arg

elif opt == '-n':

print Stock name %s % arg

sys.exit()

9、print 格式化輸出

9.1、格式化輸出字符串

截取字符串輸出,下面例子將只輸出字符串的前3個字母

>>> str=abcdefg

>>> print %.3s % str

abc

按固定寬度輸出,不足使用空格補全,下面例子輸出寬度為10

>>> str=abcdefg

>>> print %10s % str

abcdefg

截取字符串,按照固定寬度輸出

>>> str=abcdefg

>>> print %10.3s % str

abc

浮點類型數據位數保留

>>> import fpformat

>>> a= 0.0030000000005

>>> b=fpformat.fix(a,6)

>>> print b

0.003000

對浮點數四舍五入,主要使用到round函數

>>> from decimal import *

>>> a =2.26

>>> b =2.29

>>> c = Decimal(a) - Decimal(b)

>>> print c

-0.03

>>> c / Decimal(a) * 100

Decimal('-1.327433628318584070796460177')

>>> Decimal(str(round(c / Decimal(a) * 100, 2)))

Decimal('-1.33')

9.2、進制轉換

有些時候需要作不同進制轉換,可以參考下面的例子(%x 十六進制,%d 十進制,%o 八進制)

>>> num = 10

>>> print Hex = %x,Dec = %d,Oct = %o %(num,num,num)

Hex = a,Dec = 10,Oct = 12

10、Python調用系統命令或者腳本

使用 os.system() 調用系統命令 , 程序中無法獲得到輸出和返回值

>>> import os

>>> os.system('ls -l /proc/cpuinfo')

>>> os.system(ls -l /proc/cpuinfo)

-r--r--r-- 1 root root 0 3月 29 16:53 /proc/cpuinfo

0

使用 os.popen() 調用系統命令, 程序中可以獲得命令輸出,但是不能得到執行的返回值

>>> out = os.popen(ls -l /proc/cpuinfo)

>>> print out.read()

-r--r--r-- 1 root root 0 3月 29 16:59 /proc/cpuinfo

使用 commands.getstatusoutput() 調用系統命令, 程序中可以獲得命令輸出和執行的返回值

>>> import commands

>>> commands.getstatusoutput('ls /bin/ls')

(0, '/bin/ls')

11、Python 捕獲用戶 Ctrl+C ,Ctrl+D 事件

有些時候,需要在程序中捕獲用戶鍵盤事件,比如ctrl+c退出,這樣可以更好的安全退出程序

try:

do_some_func()

except KeyboardInterrupt:

print User Press Ctrl+C,Exit

except EOFError:

print User Press Ctrl+D,Exit

12、Python 讀寫文件

一次性讀入文件到列表,速度較快,適用文件比較小的情況下

track_file = track_stock.conf

fd = open(track_file)

content_list = fd.readlines()

fd.close()

for line in content_list:

print line

逐行讀入,速度較慢,適用沒有足夠內存讀取整個文件(文件太大)

fd = open(file_path)

fd.seek(0)

title = fd.readline()

keyword = fd.readline()

uuid = fd.readline()

fd.close()

寫文件 write 與 writelines 的區別

Fd.write(str) : 把str寫到文件中,write()并不會在str后加上一個換行符

Fd.writelines(content) : 把content的內容全部寫到文件中,原樣寫入,不會在每行后面加上任何東西



關鍵詞:

評論


相關推薦

技術專區

關閉