Python 命令汇总

python 库windows安装


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


#Types


a = 2           # integer
b = 3.0         # float 
c = 5.3e5       #exponential
d = 6.5 + 0.5j  # complex
e = 7 > 5       # boolean
f = '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 list
sorted([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  = 3
print(a)
a += 1   #(*=, /=)
print(a)
a *= 1
print(a)
a /= 1
print(a)
3 + 2
3/2
3//2    #integer division
3*2 
3**2    # exponent
3%2     # remainder
abs(a)  # absolute value
1 == 1  # equal
2 >1  
2 <1
1 != 2   #not equal
1 != 2 and 2 < 3  # logical AND
1 != 2 or 2 < 3 #logical OR
not  1 == 2     # logical NOT
'a' in b        # test if a is in b
a is b          # test if objects point to the same memory----简写----
a = a +1 等价于 a +=1
a = a-1  等价于 a -=1

#Control Flow


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


# if/elif/else
a, b = 1, 2
if a + b == 3:print('True')
elif a + b == 1:print('False')
else:print('?')# for 
a = ['red', 'blue', 'green']
for color in a:print(color)#while
number = 1
while number < 10:print(number)number += 1-----while -----
while 条件:do something停止办法:
改变条件,使得条件变False
使用 break 强制退出。#break
number = 1
while True:print(number)number += 1if number > 10:break#Continue
for i in range(20):if i%2 == 0:continueprint(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


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

# Function
def myfunc(a1, a2):return a1 + a2x = myfunc(a1, a2)# Class
class Point(object):def _init_(self, x):self.x = xdef _call_(self):print(self.x)x = Point(3)---类与对象  ---
类与对象,类似于 概念与实体# Generators
def firstn(n):num = 0while num < n:yield numnum += 1#Consume the generator wiht list comprehension
x = [i for i in firstn(10)]# Decorators
class myDecorator(object):def _init_(self, f):self.f = fdef _call_(self):print("call")self.f()@myDecorator
def 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 

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

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

查看软件包的版本

import xgboost
xgboost.__version__

或者

pip show xgboost

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

import django
django.VERSION

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

import xgboost
dir(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 xgboost
dir(xgboost)
type(xgboost.plotting)

模块导入


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


规则1.模块导入


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


规则2.模块导入


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


python命名规则


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


写入文件


poem = '''\
Programming is fun
When the work is done
If 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 file
f.close() #close the file  不关闭会占用系统。

读取文件


f = open('poem.txt')  #默认为'r'模式
while True:line = f.readline()if len(line) ==0:#空行表示读取结束breakprint(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:breakprint(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, shutil
if 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')
True
os.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.popenoutput = 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 random
random.shuffle (lst )
注意:shuffle()是不能直接访问的,需要导入 random 模块,然后通过 random 静态对象调用该方法
shutil.copy(src,dst)   #复制文件的内容以及权限,先copyfile后copymode#copy training data
c=0
train_label={}os.mkdir("/home/bids/miscellaneous/project/test/Xvision-master20171024/DeepLearning/final_train_images_calc_nodule_only")
for i in train_list:#print ishutil.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模块


检查软件版本


from __future__ import print_function
from distutils.version import LooseVersion as Version
import sysOK = '\x1b[42m[ OK ]\x1b[0m'
FAIL = "\x1b[41m[FAIL]\x1b[0m"try:import importlib
except ImportError:print(FAIL, "Python version 3.4 (or 2.7) is required,"" but %s is installed." % sys.version)def import_version(pkg, min_ver, fail_msg=""):mod = Nonetry:mod = importlib.import_module(pkg)if pkg in {'PIL'}:ver = mod.VERSIONelse:ver = mod.__version__if Version(ver) < min_ver:print(FAIL, "%s version %s or higher required, but %s installed."% (lib, min_ver, ver))else:print(OK, '%s version %s' % (pkg, ver))except ImportError:print(FAIL, '%s not installed. %s' % (pkg, fail_msg))return mod# first check the python version
print('Using python in', sys.prefix)
print(sys.version)
pyversion = Version(sys.version)
if pyversion >= "3":if pyversion < "3.4":print(FAIL, "Python version 3.4 (or 2.7) is required,"" but %s is installed." % sys.version)
elif pyversion >= "2":if pyversion < "2.7":print(FAIL, "Python version 2.7 is required,"" but %s is installed." % sys.version)
else:print(FAIL, "Unknown Python version: %s" % sys.version)print()
requirements = {'numpy': "1.6.1", 'scipy': "0.9", 'matplotlib': "1.0",'IPython': "3.0", 'sklearn': "0.19", 'pandas': "0.18",'seaborn': "0.5", 'PIL': "1.1.7"}# now the dependencies
for lib, required_version in list(requirements.items()):import_version(lib, required_version)

这里写图片描述


References


1小时入门Python
Python学习教程

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/246705.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【PTVS+Theano+CPU/GPU】在windows下使用VS安装theano深度学习工具

唉。好不容易折腾完毕caffe&#xff0c;突然发现caffe比较适合搭建卷积神经网络&#xff0c;而对于DBN和LSTM的搭建好像比较麻烦&#xff0c;相关教程没有找到&#xff0c;手头上又有一个theano的代码想调试看看&#xff0c;所以入坑了。 准备工具&#xff1a; VS2013:链接&a…

人工神经网络——【BP】反向传播算法证明

第一步&#xff1a;前向传播 【注】此BP算法的证明仅限sigmoid激活函数情况。本博文讲道理是没错的&#xff0c;毕竟最后还利用代码还核对了一次理论证明结果。 关于更为严谨的BP证明&#xff0c;即严格通过上下标证明BP的博客请戳这里 简单的三层网络结构如下 参数定义&…

【caffe-Windows】微软官方caffe之 matlab接口配置

前言 按照微软的官方地址配置可能会出现一个问题caffe_.mexw64找不到引用模块问题&#xff0c;或者在matlab里面压根找不到caffe_这个函数&#xff0c;下面会提到这两个问题。还是按照步骤来吧 【PS1】有GPU同样按照下述步骤&#xff0c;进行即可 【PS2】文章在matlab2013a、…

【混淆矩阵】matlab画混淆矩阵

主要借鉴此博客代码&#xff1a;http://blog.csdn.net/sherry_gp/article/details/50560003 但是这个博主的代码达不到我想要的效果&#xff0c;所以修改了一下 我想要实现的效果是&#xff1a;给定一列的预测标签&#xff0c;以及这一列标签的哪一部分理应属于哪一部分标签。…

【caffe-Windows】mnist实例编译之model的生成

其实这个和cifar的实例基本相同&#xff0c;只不过数据转换的方法不一样 【说明&#xff0c;此博客按照我自己的路径设置的相关操作&#xff0c;读者如果自行选择其他路径&#xff0c;记得在bat和prototxt等文件修改路径】 第一步 下载数据集THE MNIST DATABASE of handwrit…

吉布斯采样——原理及matlab实现

原文来自&#xff1a;https://victorfang.wordpress.com/2014/04/29/mcmc-the-gibbs-sampler-simple-example-w-matlab-code/ 【注】评论区有同学指出译文理论编码有误&#xff0c;请参考更官方的文献&#xff0c;个人当时仅验证过红色字体部分理论与维基百科中二位随机变量吉…

【matlab知识补充】conv2、filter2、imfilter函数原理

原文地址&#xff1a;http://www.ilovematlab.cn/thread-293710-1-1.html -------------------------------------conv2函数---------------------------------------- 1、用法 Cconv2(A,B,shape); %卷积滤波 复制代码A:输入图像&#xff0c;B:卷积核假设输入图像A大…

显示mnist手写数字

前言 可视化什么的&#xff0c;总是好的 方法一 其实也就是用到了Ruslan Salakhutdinov and Geoff Hinton提供的工具包 % Version 1.000 % % Code provided by Ruslan Salakhutdinov and Geoff Hinton % % Permission is granted for anyone to copy, use, modify, or distr…

【caffe-Windows】mnist实例编译之model的使用-classification

仿照cifar10的模型使用&#xff0c;本文对mnist的训练方式做了部分修改 【注】本文caffe安装路径为E:\CaffeDev-GPU\caffe-master。请自行参考并修改相关路径(debug以及release参考你编译caffe时候采用的模式) 第一步 按照前面的model生成方法的前两步骤制作数据集&#xff…

误差error,偏置bias,方差variance的见解

更新日志&#xff1a;2020-3-10 谢谢ProQianXiao的指正。偏差-方差的确是在测试集中进行的。 之前的误解是&#xff0c;偏差和方差的计算是同一个模型对不同样本的预测结果的偏差和方差&#xff1b;而实际上是不同模型对同一个样本的预测结果的偏差和方差。 这时候就要祭出网…

【caffe-Windows】以mnist为例lmdb格式数据

前言 前面介绍的案例都是leveldb的格式&#xff0c;但是比较流行和实用的格式是lmdb&#xff0c;原因从此网站摘取 它们都是键/值对&#xff08;Key/Value Pair&#xff09;嵌入式数据库管理系统编程库。虽然lmdb的内存消耗是leveldb的1.1倍&#xff0c;但是lmdb的速度比level…

【caffe-Windows】mnist实例编译之model的使用-matlab

前言 针对上一个caffe文章留下的matlab手写数字识别的问题&#xff0c;感谢caffe中文社区的 ghgzh 的提示&#xff0c;原文请看&#xff1a;caffe中文社区 第一步 手写图片的制作方法我就不说了&#xff0c;直接把我自己画的几个数字放到云盘先&#xff1a; 三通道图像以及…

【caffe-Windows】训练自己数据——数据集格式转换

前言 看了mnist和cifar的实例&#xff0c;是不是想我们现实中一般都是一张张的图片&#xff0c;和实例里面都不一样呢&#xff1f;那么如何来进行训练呢&#xff1f;为了能够简便点&#xff0c;我们就不自己去采集数据集了&#xff0c;因为第一自己采集的数据集量可能不够&…

【caffe-windows】Linux至Windows平台的caffe移植

1、前言 主要参考两篇博客以及很多论坛解决细节问题&#xff1a; http://www.cnblogs.com/trantor/p/4570097.html https://initialneil.wordpress.com/2015/01/11/build-caffe-in-windows-with-visual-studio-2013-cuda-6-5-opencv-2-4-9/ 移植环境&#xff1a;Windows7…

【caffe-matlab】权重以及特征图的可视化

前言 移植了各种caffe&#xff0c;是时候进行下一步操作了&#xff0c;先拿可视化下手吧。大部分内容可能跟网上的方法不一样&#xff0c;大家看完我的博客最好去网上看看大牛们的博客&#xff0c;万一被我误导了&#xff0c;就罪过了o(╯□╰)o&#xff0c;开更.............…

【caffe-matlab】使用matlab训练caffe及绘制loss

前言 此博客主要介绍如何利用matlab一步一步训练caffe模型&#xff0c;类似使用caffe.exe 的train命令。 国际惯例&#xff0c;参考博客&#xff1a; http://caffe.berkeleyvision.org/tutorial/interfaces.html http://www.cnblogs.com/denny402/p/5110204.html 抱怨一…

【caffe-matlab】目标检测R-FCN算法于Windows下配置

前言 首先谢谢好友推荐的这篇论文及代码&#xff0c;前面学习的caffe可能比较浅显&#xff0c;想要深入caffe就可以从这个代码下手了&#xff0c;配置方法还是挺简单的&#xff0c;但是可能会出现部分问题。在作者的论文中有github的地址。注意&#xff0c;本文只介绍如何配置…

【写作】Texlive和Texmaker学习

前言 最近要看一些论文做一下笔记&#xff0c;所以准备使用一下比较流行的Texlive和Texmaker写一下。其实CSDN的Markdown也是不错滴。 首先国际惯例&#xff0c;贴几个地址&#xff1a; Texlive镜像下载地址&#xff1a;http://mirror.lzu.edu.cn/CTAN/systems/texlive/Imag…

《Neural Networks for Machine Learning》学习一

前言 最近报了一下Hinton大牛的coursera的神经网络课程&#xff0c;奈何比较懒&#xff0c;一直没看&#xff0c;还是写个博客督促自己比较好 贴一下课程地址&#xff1a;https://www.coursera.org/learn/neural-networks/home/week/1 第一讲主题是为何需要机器学习&#xf…

《Neural Networks for Machine Learning》学习二

前言 课程地址&#xff1a;https://www.coursera.org/learn/neural-networks/home/week/1‘’ 【Lecture 2】百度云下载地址&#xff1a;链接&#xff1a;http://pan.baidu.com/s/1nvMynhR 密码&#xff1a;ru3y 神经网络架构概览 前馈神经网络(Feed-Forward neural network)…