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):列表元素个数
3、max(list):返回列表元素最大值
4、min(list):返回列表元素最小值
5、list(seq):将元组转换为列表

列表操作包含以下方法:
1、list.append(obj):在列表末尾添加新的对象
2、list.count(obj):统计某个元素在列表中出现的次数
3、list.extend(seq):在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
4、list.index(obj):从列表中找出某个值第一个匹配项的索引位置
5、list.insert(index, obj):将对象插入列表
6、list.pop(obj=list[-1]):移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
7、list.remove(obj):移除列表中某个值的第一个匹配项
8、list.reverse():反向列表中元素
9、list.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)------break 和 continue   -------
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学习教程

Python 命令汇总相关推荐

  1. python命令大全下载-Python pip 常用命令汇总

    使用了这么就pip命令,但是一直是简单使用,很多命令都是用了查,查了用,今天把常用的命令汇总一下,方便使用. 命令: pip 由上图可以看到 pip 支持一下命令 Commands: install ...

  2. python常用命令大全-Python pip 常用命令汇总

    使用了这么就pip命令,但是一直是简单使用,很多命令都是用了查,查了用,今天把常用的命令汇总一下,方便使用. 命令: pip 由上图可以看到 pip 支持一下命令 Commands: install ...

  3. Python初学者请注意!别这样直接运行python命令,否则电脑等于“裸奔”

    晓查 编译整理  量子位 报道 | 公众号 QbitAI Python已经成为全球最受欢迎的编程语言之一.原因当然是Python简明易用的脚本语法,只需把一段程序放入.py文件中,就能快速运行. 而且 ...

  4. python第三方库排行-Python模块汇总(常用第三方库)

    模块 定义 计算机在开发过程中,代码越写越多,也就越难以维护,所以为了编写可维护的代码,我们会把函数进行分组,放在不同的文件里.在python里,一个.py文件就是一个模块 优点: 提高代码的可维护性 ...

  5. python编程语法大全-python语法汇总

    广告关闭 2017年12月,云+社区对外发布,从最开始的技术博客到现在拥有多个社区产品.未来,我们一起乘风破浪,创造无限可能. splitstriplen()for variable in range ...

  6. 2013流行Python项目汇总

    2013流行Python项目汇总 转自:http://www.kankanews.com/ICkengine/archives/102963.shtml Python作为程序员的宠儿,越来越得到人们的 ...

  7. xshell删除文件夹命令_ssh远程连接GPU服务器进行深度学习以及常用ssh命令汇总

    在我们进行深度学习的科研任务时,我们都会遇到复杂神经网络的训练问题,这时我们都不可避免地需要一块合适的gpu服务器,我认为gpu服务器的好处有两点:一是相对而言便宜一些,虽然很多gpu服务器也是昂贵的 ...

  8. 【批处理DOS-CMD命令-汇总和小结】-跳转、循环、条件命令(goto、errorlevel、if、for[读取、切分、提取字符串]、)cmd命令错误汇总,cmd错误

    一.本文摘要 此文主要研究对代码分支化执行和重复利用的实现. 分支化执行指根据中途的实际执行结果决定下一步执行的代码,跳转的代码行号:分支化执行大概分为跳转执行.条件判断执行:因此,分支化执行基本是只 ...

  9. git 实践命令汇总

    2019独角兽企业重金招聘Python工程师标准>>> git 实践命令汇总 stash 获取 stash 列表 git stash list 清除 stash git stash ...

最新文章

  1. Gartner:人工智能将促使部分专业工作转型
  2. 查找字符位置_Excel中查找字符第N次出现的位置信息,换个思路其实很简单
  3. centos 7 ldap php7,centOS更新php7
  4. 简单粗暴的入门机器学习
  5. Redis 缓存常见问题:缓存一致性的解决方案
  6. 电脑自带 超强系统文件自检 分享
  7. 图片处理--熔铸特效
  8. 【实战练习】通过docker部署jenkins
  9. 使用Genymotion Android模拟器无法连接电脑本机的服务器
  10. 优秀课件笔记之文件系统
  11. 异常与调试之SEH、UEH、VEH、VCH以及SEH原理
  12. 【jQwidgets】jqxComboBox
  13. HTML+css制作简单游戏界面
  14. Win10 Build 18237发布:登录屏幕启用毛玻璃特效
  15. 阿波罗数据集怎么下载_百度阿波罗发布全球最大的无人驾驶汽车数据集
  16. 引导魔女之力,征服星辰大海 主线篇: 重要事情说三遍: 推主线!推主线!!推主线!!! 简述: 1.本篇仅主线,涉及到的技巧全职业都可以参考; 2.考虑到萌新刚玩没有护卫者系统,故禁护
  17. 22河师大上岸经验贴
  18. sbrkr.c:(.text._sbrk_r+0xc): undefined reference to `_sbrk'
  19. win10关闭实时防护的步骤教程
  20. 肖秀荣教授:就考研政治来说

热门文章

  1. linux错误代码0x8008005,利用Windows10自带Linux学习(附带:0x8007019e错误解决方法)...
  2. linux以预置密码进行验证拒绝访问,Linux重置MySQL密码
  3. 带防夹功能的升降器原理_桌面光污染必不可少——骨伽Bunker RGB鼠标线夹
  4. python爬虫实践 —— 一、入门篇
  5. impdp导入表结构和表数据_ORACLE数据库如何用datapump工具导出表结构然后导入到其它Schema下面...
  6. activiti高亮显示图片_第 09 篇:让博客支持 Markdown 语法和代码高亮
  7. 图论--拓扑排序--HDU-1285确定比赛名次
  8. 数学--数论--快速乘法+快速幂
  9. JLINK与JTAG的区别
  10. vmware上安装vxworks(xp环境)