Python 命令汇总

来源:互联网 发布:windows正版激活工具 编辑:程序博客网 时间:2024/05/22 12:09

兵种:python程序员。
等级:二级。
攻击:较高。
防御:普通。
价格:低。
天赋:胶水,我方有c程序员时,速度可达到c程序员的80%。
天赋:成熟,难以升级到三级,即使成功也没什么好处
—–刘鑫Mars


#Types


a = 2           # integerb = 3.0         # float c = 5.3e5       #exponentiald = 6.5 + 0.5j  # complexe = 7 > 5       # booleanf = 'helloword'      # string

# Lists


a = ['red', 'blue', 'green']   b = list(range(5)) c = [nu**2 for nu in b]d = [nu**2 for nu in b if nu <3]e = c[0]f = c[1:2]g = ['re', 'bl'] + ['gr']h = ['re']*5['re','bl'].index('re')         #returns index of 're''re' in ['re', 'bl']            #true if 're' in listsorted([3,4,1])                 #returns sorted list----列表中的元素可以是相同的类型,也可以是不同类型的。a =[1, "b", 3, 6, "google", True]-----列表中插入或者删除元素-----a.insert(3, "fire") #插入到类别中第四个位置a.append("ch")  # 插入到列表的最后面del a[2]     #删除列表中的第三个元素['Hi!'] * 4     ['Hi!', 'Hi!', 'Hi!', 'Hi!']    重复
列表操作包含以下函数:1、cmp(list1, list2):比较两个列表的元素2、len(list):列表元素个数3max(list):返回列表元素最大值4min(list):返回列表元素最小值5list(seq):将元组转换为列表
列表操作包含以下方法:1list.append(obj):在列表末尾添加新的对象2list.count(obj):统计某个元素在列表中出现的次数3list.extend(seq):在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)4list.index(obj):从列表中找出某个值第一个匹配项的索引位置5list.insert(index, obj):将对象插入列表6list.pop(obj=list[-1]):移除列表中的一个元素(默认最后一个元素),并且返回该元素的值7list.remove(obj):移除列表中某个值的第一个匹配项8list.reverse():反向列表中元素9list.sort([func]):对原列表进行排序

Tuple


元组是不能增加或删除元素,类似于常量。
(2,) #一个元素的元组


# Dictionaries


字典是一种映射,从key 到value 的一种映射。

a = {'red': 'rouge', 'blue':'bleu', 'green': 'vertet'} b = a['red']  #字典取值c = [value for key, value in a.items()]d = a.get('yellow', 'no translation found')

#Strings


字符串其实是一个特殊的列表,列表中每个元素是一个字符。字符串本质上是一个常量,可以查询,不能修改。

a = 'red'char = a[2]'red' + 'blue''1, 2, three'.split(',')     # split string into list'.'.join(['1', '2', 'three']) # concatenate list into string

%占位符
a = “hello %s” % “wang”
a =”%s %s” % (“hello”, “wang”)
a =”%(verb)s %(name)s” % {“verb”: “hello”, “name” : “wang”} #占位符命名


# Operators


a  = 3print(a)a += 1   #(*=, /=)print(a)a *= 1print(a)a /= 1print(a)3 + 23/23//2    #integer division3*2 3**2    # exponent3%2     # remainderabs(a)  # absolute value1 == 1  # equal2 >1  2 <11 != 2   #not equal1 != 2 and 2 < 3  # logical AND1 != 2 or 2 < 3 #logical ORnot  1 == 2     # logical NOT'a' in b        # test if a is in ba is b          # test if objects point to the same memory----简写----a = a +1 等价于 a +=1a = a-1  等价于 a -=1

#Control Flow


控制流是能够改变代码执行顺序的。

# if/elif/elsea, b = 1, 2if a + b == 3:    print('True')elif a + b == 1:    print('False')else:    print('?')# for a = ['red', 'blue', 'green']for color in a:    print(color)#whilenumber = 1while number < 10:    print(number)    number += 1-----while -----while 条件:    do something停止办法:改变条件,使得条件变False使用 break 强制退出。#breaknumber = 1while True:    print(number)    number += 1    if number > 10:        break#Continuefor i in range(20):    if i%2 == 0:        continue        print(i)------breakcontinue   -------row =[1, 2, 4, 6, 8]for item in row:    if item ==2:         continue        #跳过后面两句,只是跳出本次循环。    if item == 4:    break          #break使整个for 循环结束

# Functions, Classes, Generators, Decorators


所谓函数,就是多个命令的组合体。

# Functiondef myfunc(a1, a2):    return a1 + a2x = myfunc(a1, a2)# Classclass Point(object):    def _init_(self, x):        self.x = x    def _call_(self):        print(self.x)x = Point(3)---类与对象  ---类与对象,类似于 概念与实体# Generatorsdef firstn(n):    num = 0    while num < n:        yield num        num += 1#Consume the generator wiht list comprehensionx = [i for i in firstn(10)]# Decoratorsclass myDecorator(object):    def _init_(self, f):        self.f = f    def _call_(self):        print("call")        self.f()@myDecoratordef my_funct():    print('func')my_funct()

函数中的参数

形参: 
def clean_room(room_name):
clean_table(room_name)
clean_floor(room_name)
clear_trash(room_name)

clean_room(“主卧”)

位置参数: 依据位置赋值。
def clean_room(room_name, level):
# clear code

clean_room(“主卧”, 2)

关键字参数: 明确指出传入给某个参数。
def clean_room(room_name, level):
#clean code

clean_room(level = 2, room_name =”主卧”)
关键字参数不局限位置信息。

默认参数: 
def clean_room(room_name, level =2):
#clean code

clean_room(“主卧”)

返回值: 
def clean_room(room_name, level =2):
#clean code
finished = True
return finished

success = clean_room(room_name =”主卧”)
无return 语句,默认返回 None.

多返回值: 
def clean_room(room_name, level =2):
#clean code
finished = True
error_msg = “清洁剂没有了”
return finished, error_msg

success, msg = clean_room(room_name =”主卧”)
无return 语句,默认返回 None.

文档字符串: 
def clean_room(room_name, level =2):
”’
这个函数用来清理房间  #文档字符串
”’
#clean code
finished = True
error_msg = “清洁剂没有了”
return finished, error_msg

success, msg = clean_room(room_name =”主卧”)
无return 语句,默认返回 None.


# IPython


# Python console<object>? # Information about the object<object>.<TAB>  # tab completion# measure runtime of a function:%timeit range(1000)100000 loops, best of 3: 7.76 us per loop# run scripts and debug%run %run -d  # run in debug mode%run -t  # measures execution time %run -p # ruans a profiler%debug # jumps to debugger after an exception%pdb  # run debugger automatically on exception # examine history%history%history ~1/1-5  # lines 1-5 of last session# run shell commands!make # prefix command with "!"#clean namespace%reset

查看Python软件包信息


可以查看已经安装的python软件包和版本

pip freeze  pip list 

查看软件包源代码所在位置

pythonimport xgboostxgboost.__file__  #查看xgboost包的__init__.py文档所在位置

查看软件包的版本

import xgboostxgboost.__version__

或者

pip show xgboost

不同软件包的属性不一样,有的查询版本可使用

import djangodjango.VERSION

查看模块的属性
本质上是一个变量。

import xgboostdir(xgboost)
['Booster', 'DMatrix', 'VERSION_FILE', 'XGBClassifier', 'XGBModel', 'XGBRegressor', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__version__', 'absolute_import', 'callback', 'compat', 'core', 'cv', 'libpath', 'os', 'plot_importance', 'plot_tree', 'plotting', 'rabit', 'sklearn', 'to_graphviz', 'train', 'training']

查看模块的属性类型

import xgboostdir(xgboost)type(xgboost.plotting)

模块导入


模块被导入时,代码会运行一次。再次导入,不会再次运行。


规则1.模块导入


跟入口文件在同一个目录下。


规则2.模块导入


. 表示当前模块所在的包下。
.. 表示当前模块的所在包的外层目录下。


python命名规则


命名只能是数字、字母和下划线。数字不能开头,区分大小写。


写入文件


poem = '''\Programming is funWhen the work is doneIf you want to make your work also fun:use Python!'''f = open('poem.txt','w') # 模式:'w'写入 write,'r'读取read,'a'追加 append#open 返回的是文件夹表示符f.write(poem) # write text to filef.close() #close the file  不关闭会占用系统。

读取文件


f = open('poem.txt')  #默认为'r'模式while True:     line = f.readline()     if len(line) ==0:#空行表示读取结束     break     print(line, end="")     #print 内容后面默认会增加一个\n     #这里end禁止结尾增加\n,改为增加""f.close() #close the file  

with语句


写入文件

with open('poem.txt','w') as f:    f.write(poem)

读取文件

with open('poem.txt') as f:    while True:    line = f.readline()    if len(line) == 0:       break    print(line, end="")

异常处理


try:   一段可能出错的代码expect ValueError as e:   print(e) # 处理这个异常except Exception:   处理其余所有的异常else:没有异常的处理代码
try:     一段可能出错的代码finally:     最后一定会执行的代码,例如     f.close()
try:    int("a")except ValueError as e:    print(e)    raise e   # 抛出异常

python函数


Python lower()方法

描述

Python lower() 方法转换字符串中所有大写字符为小写。

#!/usr/bin/pythonstr = "THIS IS STRING EXAMPLE....WOW!!!";print str.lower();
this is string example....wow!!!

Python清空指定文件夹下所有文件的方法

    import shutil      shutil.rmtree('要清空的文件夹名')      os.mkdir('要清空的文件夹名')  

python shutil模块学习

python判断文件和文件夹是否存在、创建文件夹

#判断是否存在路径import os, shutilif os.path.exists('/home/bids/test/wang'):   shutil.rmtree('/home/bids/test/wang')   os.makedirs('/home/bids/test/wang') else:   os.makedirs('/home/bids/test/wang')
#判断是否为文件os.path.isfile('/home/bids/test/a.py')Trueos.path.isfile('/home/bids/test')False#判断是否为目录#os.path.isdir()函数判断某一路径是否为目录。#其函数原型如下所示:os.path.isdir(path)#其参数 path为 要进行判断的路径。如果是则返回TRUE,否则返回FALSE

创建多级目录

1.mkdir( path [,mode] )      作用:创建一个目录,可以是相对或者绝对路径,mode的默认模式是0777。      如果目录有多级,则创建最后一级。如果最后一级目录的上级目录有不存在的,则会抛出一个OSError。 2.makedirs( path [,mode] )      作用: 创建递归的目录树,可以是相对或者绝对路径,mode的默认模式也是0777。      如果子目录创建失败或者已经存在,会抛出一个OSError的异常,Windows上Error 183即为目录已经存在的异常错误。如果path只有一级,与mkdir一样。

删除目录及多级目录

#os.rmdir()函数删除目录。#其原型如下所示:os.rmdir(path)#其参数path 为要删除的目录的路径。#注意:要删除的目录必须是空目录#os.removedirs()函数删除多级目录。#其原型如下所示:os.removdirs(path)#其参数path 为要删除的多级目录的路径。#注意:要删除的目录必须是空目录shutil.rmtree(path)#空目录、有内容的目录都可以删,但只删除最后一级目录

Python执行系统命令

#os.system()    result = os.system('cat /proc/cpuinfo') #linux      result = os.system('ipconfig') #windows  
#os.popen    output = os.popen('cat /proc/cpuinfo')      print output.read()      output.close()  
#commands.getstatusoutput()    (status, output) = commands.getstatusoutput('cat /proc/cpuinfo')      print status, output      output.close()  

%matplotlib inline是jupyter notebook里的命令, 意思是将那些用matplotlib绘制的图显示在页面里而不是弹出一个窗口.
magic函数分两种:一种是面向行的,另一种是面向单元型的。


python常用函数


# 查看当前工作目录retval = os.getcwd()

os.chdir() 方法用于改变当前工作目录到指定的路径

语法chdir()方法语法格式如下:os.chdir(path)参数    path -- 要切换到的新路径。返回值如果允许访问返回 True , 否则返回False

shuffle() 方法将序列的所有元素随机排序

#以下是 shuffle() 方法的语法:import randomrandom.shuffle (lst )注意:shuffle()是不能直接访问的,需要导入 random 模块,然后通过 random 静态对象调用该方法
shutil.copy(src,dst)   #复制文件的内容以及权限,先copyfile后copymode#copy training datac=0train_label={}os.mkdir("/home/bids/miscellaneous/project/test/Xvision-master20171024/DeepLearning/final_train_images_calc_nodule_only")for i in train_list:     #print i    shutil.copy('/home/bids/miscellaneous/project/test/Xvision-master20171024/scraper/data/'+i+'.png', '/home/bids/miscellaneous/project/test/Xvision-master20171024/DeepLearning/final_train_images_calc_nodule_only/'+str(c)+'.png')    train_label[c] = new_image_dict[i]    c+=1

python之模块之shutil模块


References


1小时入门Python
Python学习教程

0 0
原创粉丝点击