Python语言的12个基础知识点小结

张开发
2026/6/26 21:03:13 15 分钟阅读
Python语言的12个基础知识点小结
python与R语言的一些语法比较作为一个R语言使用者要转战到python还是需要一个适应过程的有几个比较容易忘记的点python区分大小写而R对大小写不敏感python中的索引是从0开始的而R是从1开始的安装包的方式不同R是用install.packages()使用时用library(包名进行加载而python是用import导入对应的模块再从模块中加载函数或属性自定义函数时R中return函数需要加括号python不需要python基本知识点梳理python编程中常用的12种基础知识总结正则表达式替换遍历目录方法列表按列排序、去重、字典排序、字典、列表、字符串互转时间对象操作命令行参数解析(getopt)print 格式化输出进制转换Python调用系统命令或者脚本Python 读写文件。正则表达式替换目标: 将字符串line中的 overview.gif 替换成其他字符串。line ‘IMG SRC’#‘ /’more.compile(r’(?SRC)“([\w.])”‘,re.I)mo.sub(r’“\1****”‘,line)‘IMG SRC’#’ /spanmo.sub(r’replace_str_\1’,line)‘遍历目录方法在某些时候我们需要遍历某个目录找出特定的文件列表可以通过os.walk方法来遍历非常方便。import osfileList []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列表按列排序(list sort)如果列表的每个元素都是一个元组(tuple),我们要根据元组的某列来排序的化可参考如下方法下面例子我们是根据元组的第2列和第3列数据来排序的而且是倒序(reverseTrue)。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-17b sorted(a, keylambda result: result[1],reverseTrue)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, keylambda result: result[2],reverseTrue)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 itemgetteraa {“a”:“1”,“sss”:“2”,“ffdf”:‘5’,“ffff2”:‘3’}sort_aa sorted(aa.items(),keyitemgetter(1))sort_aa[(‘a’, ‘1’), (‘sss’, ‘2’), (‘ffff2’, ‘3’), (‘ffdf’, ‘5’)]6、字典列表字符串互转以下是生成数据库连接字符串从字典转换到字符串。params {“server”:“mpilgrim”, “database”:“master”, “uid”:“sa”,“pwd”:“secret”}[“%s%s” % (k, v) for k, v in params.items()][‘servermpilgrim’, ‘uidsa’, ‘databasemaster’, ‘pwdsecret’]“;”.join([“%s%s” % (k, v) for k, v in params.items()])‘servermpilgrim;uidsa;databasemaster;pwdsecret’下面的例子是将字符串转化为字典。a ‘servermpilgrim;uidsa;databasemaster;pwdsecret’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 datetimedatetime.datetime.now().strftime(“%Y-%m-%d %H:%M”)‘2011-01-20 14:05’时间大小比较。import timet1 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 t2Falset1 t2True时间差值计算计算8小时前的时间。datetime.datetime.now().strftime(“%Y-%m-%d %H:%M”)‘2011-01-20 15:02’(datetime.datetime.now() - datetime.timedelta(hours8)).strftime(“%Y-%m-%d %H:%M”)‘2011-01-20 07:03’将字符串转换成时间对象。endtimedatetime.datetime.strptime(‘20100701’,“%Y%m%d”)type(endtime)type ‘datetime.datetime’print endtime2010-07-01 00:00:00将从 1970-01-01 00:00:00 UTC 到现在的秒数格式化输出。import timea 1302153828time.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,getoptdef 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 infotest.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” % argelif opt ‘-f’:print “read file %s” % argelif opt ‘-c’:print user-defined %s % argelif opt ‘-e’:print “Exchange Name %s” % argelif opt ‘-s’:print “Stock code %s” % argelif opt ‘-n’:print “Stock name %s” % argsys.exit()9、print 格式化输出9.1、格式化输出字符串截取字符串输出下面例子将只输出字符串的前3个字母。str“abcdefg”print “%.3s” % strabc按固定宽度输出不足使用空格补全下面例子输出宽度为10。str“abcdefg”print “%10s” % strabcdefg截取字符串按照固定宽度输出。str“abcdefg”print “%10.3s” % strabc浮点类型数据位数保留。import fpformata 0.0030000000005bfpformat.fix(a,6)print b0.003000对浮点数四舍五入主要使用到round函数。from decimal import *a “2.26”b “2.29”c Decimal(a) - Decimal(b)print c-0.03c / Decimal(a) * 100Decimal(‘-1.327433628318584070796460177’)Decimal(str(round(c / Decimal(a) * 100, 2)))Decimal(‘-1.33’)9.2、进制转换有些时候需要作不同进制转换可以参考下面的例子(%x 十六进制%d 十进制%o 十进制)。num 10print “Hex %x,Dec %d,Oct %o” %(num,num,num)Hex a,Dec 10,Oct 1210、Python调用系统命令或者脚本使用 os.system() 调用系统命令 , 程序中无法获得到输出和返回值。import osos.system(‘ls -l /proc/cpuinfo’)os.system(“ls -l /proc/cpuinfo”)-r–r–r-- 1 root root 0 3月 29 16:53 /proc/cpuinfo0使用 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 commandscommands.getstatusoutput(‘ls /bin/ls’)(0, ‘/bin/ls’)11、Python 捕获用户 CtrlC ,CtrlD 事件有些时候需要在程序中捕获用户键盘事件比如ctrlc退出这样可以更好的安全退出程序。try:do_some_func()except KeyboardInterrupt:print “User Press CtrlC,Exit”except EOFError:print “User Press CtrlD,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的内容全部写到文件中原样写入不会在每行后面加上任何东西。文章来源网络 版权归原作者所有上文内容不用于商业目的如涉及知识产权问题请权利人联系小编我们将立即处理

更多文章