宁波网站建设托管17zwd一起做业网站
news/
2025/9/23 7:44:07/
文章来源:
宁波网站建设托管,17zwd一起做业网站,网站制作找哪个,一个网站怎么赚钱python 库windows安装 兵种#xff1a;python程序员。 等级#xff1a;二级。 攻击#xff1a;较高。 防御#xff1a;普通。 价格#xff1a;低。 天赋#xff1a;胶水#xff0c;我方有c程序员时#xff0c;速度可达到c程序员的80%。 天赋#xff1a;成熟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(objlist[-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 consoleobject? # 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) 模块导入 模块被导入时代码会运行一次。再次导入不会再次运行。 规则模块导入 跟入口文件在同一个目录下。 规则模块导入 . 表示当前模块所在的包下。 .. 表示当前模块的所在包的外层目录下。 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写入 writer读取reada追加 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
c0
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]c1
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[0mtry: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/911810.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!