![](https://img-blog.csdnimg.cn/20201014180756724.png?x-oss-process=image/resize,m_fixed,h_64,w_64)
Python
Python学习笔记
小林书店副编集
此人不懒,什么都没有写
展开
-
sklearn 中的 r2_score
R2R^2R2不止一种定义方式,这里是scikit-learn中所使用的定义。As such variance is dataset dependent, R² may not be meaningfully comparable across different datasets. Best possible score is 1.0 and it can be negative (because the model can be arbitrarily worse). A constant model原创 2020-06-29 19:21:49 · 1546 阅读 · 3 评论 -
Python的Iterator可以同时打印信息
Python的Iterator可以同时打印信息Updated: May 12, 2020 5:58 PM今天看到一个Python Iterator的高级用法,之前并不知道,孤陋寡闻了。def my_gen(): for i in range(10): print(f"This is {i}") yield i上面这个iterator会在每次循环过程中打印信息,但是返回值依然是i。也就是说,b = np.linspace(0, 100, num=10)a =原创 2020-05-13 00:02:19 · 286 阅读 · 0 评论 -
pandas根据index操作与重新排列
pandas有三个操作index的方法reindexDataFrame.reindex(self, labels=None, index=None, columns=None, axis=None, method=None, copy=True, level=None, fill_value=nan, limit=None, tolerance=None)reset_indexDataFrame.reset_index(self, level: Union[Hashable, Sequen原创 2020-05-08 19:37:06 · 1685 阅读 · 0 评论 -
无需循环合并list里的所有numpy.array
numpy.stack(list, axis=0 )或更简单地 numpy.vstack(list)以上代码可以将list中的所有numpy.array进行合并,无需循环。原创 2020-05-06 02:19:29 · 3999 阅读 · 1 评论 -
Python的"random"函数的使用(一)
random.randrange(1,10)随机产生0~7之间的整数,不包含7。random.sample(range(100), 5)随机从range(100)中产生5个数,放入一个list。random.choice()possiblePets = ['Cat', 'Dog', 'Fish']print(random.choice(possiblePets))从pos...原创 2017-07-02 15:16:00 · 96 阅读 · 0 评论 -
Python中的"Special Method"
The first thing to know about special methods is that they are meant to be called by the Python interpreter, and not by you. You don’t write my_object.len(). You write len(my_object) and, if my...原创 2017-07-01 18:25:00 · 98 阅读 · 0 评论 -
理解Python中的继承规则和继承顺序
先来看一段代码:class First(object): def __init__(self): print ("first")class Second(object): def __init__(self): print ("second")class Third(object): def __init__(self...原创 2017-06-23 18:04:00 · 86 阅读 · 0 评论 -
Python私有变量(Private Variable)
Variables can be private which can be useful on many occasions. A private variable can only be changed within a class method and not outside of the class.Objects can hold crucial data for you...原创 2017-06-24 22:00:00 · 253 阅读 · 0 评论 -
Python重写父类方法__len__
class Liar(list): def __len__(self): return super().__len__() + 3 # 直接写 super().__len__() 而没有 return 不会返回 length !a = Liar(['a','b'])原创 2017-06-24 10:45:00 · 179 阅读 · 0 评论 -
利用Python批量重命名一系列文件名杂乱的文件
假设目录下面有这样一系列命令杂乱的文件:OPENFOAM -TRAINING- PART- #1.pdfOPENFOAM - TRAINING- PART- #2.pdfOPENFOAM- TRAINING- PART-#3 .pdf不仅序号被放在最后,而且还有许多多余的空格。现在批量将这些文件重命名,去掉#,并把序号挪到最前面。import osos.ch...原创 2017-06-15 14:11:00 · 148 阅读 · 0 评论 -
理解Python中的__init__和__new__
先来看一段代码:class A(object): # -> don't forget the object specified as base def __new__(cls): print ("A. __new__ called") return super().__new__(cls) def __init__(self)...原创 2017-06-24 10:27:00 · 69 阅读 · 0 评论 -
python 在不同CPU上同时运行多个程序
出处/From https://www.quora.com/If-you-run-Python-under-a-dual-core-CPU-then-can-you-run-two-Python-programs-at-once-one-that-utilizes-1-core-and-the-other-utilizing-the-other-coreIn [24]: import ...原创 2018-10-19 20:31:00 · 358 阅读 · 0 评论 -
Python"sorted()"和".sort()"的区别
sorted(A-LIST)会返回一个新的object,不改变A-LIST*本身。A-LIST.sort()会直接改变A-List,不产生新的object**。原创 2017-07-05 15:31:00 · 76 阅读 · 0 评论 -
Python的return语句中使用条件判断
if end1 <= val <= end2 or end2 <= val <= end1: return Trueelse: return False等于return end1 <= val <= end2 or end2 <= val <= end1原创 2017-06-22 20:01:00 · 1520 阅读 · 0 评论 -
Python中Class中的object是什么意思?
https://stackoverflow.com/a/2588667/8189120In short, it sets free magical ponies.In long, Python 2.2 and earlier used "old style classes". They were a particular implementation of classes, and...原创 2017-06-20 22:21:00 · 161 阅读 · 0 评论 -
Python模块和模块引用(一)
"""import my_module as mmcourses = ['History','Math','Physics','CompSci']index = mm.find_index(courses, 'Math')print (index)""""""from my_module import find_indexcourses = ['History',...原创 2017-06-14 14:08:00 · 95 阅读 · 0 评论 -
Dictonary(Python)(一)
基本用法:.keys.values.items>>> D = dict(a=1,b=2,c=3)>>> D{'a': 1, 'b': 2, 'c': 3}>>> D.keys<built-in method keys of dict object at 0x1022ceaf8>>>>...原创 2017-06-11 17:19:00 · 106 阅读 · 0 评论 -
Map、Filter和Reduce函数(Python)
Mapmap(function_to_apply, list_of_inputs)设有以下代码:>>> items = [1, 2, 3, 4, 5]>>> squared = []>>> for i in items:... squared.append(i**2)... >>> squar...原创 2017-06-11 16:06:00 · 66 阅读 · 0 评论 -
Python中使用"subplot"在一张画布上显示多张图
subplot(arg1, arg2, arg3)arg1: 在垂直方向同时画几张图arg2: 在水平方向同时画几张图arg3: 当前命令修改的是第几张图t = np.arange(0,5,0.1)y1 = np.sin(2*np.pi*t)y2 = np.sin(2*np.pi*t)plt.subplot(211)plt.plot(t,y1,'b-.')plt.sub...原创 2017-07-02 20:10:00 · 1662 阅读 · 0 评论 -
Python/Numpy 矩阵运算符号@
A = np.matrix('3 1; 8 2')B = np.matrix('6 1; 7 9')A@Bmatrix([[25, 12], [62, 26]])原创 2020-04-22 16:30:00 · 1785 阅读 · 0 评论 -
Python 3.5以上版本合并两个Dict
x = {'a': 1, 'b': 2} y = {'b': 3, 'c': 4} z = {**x, **y}输出结果{'a': 1, 'b': 3, 'c': 4}注意:如果key相同,第二个dict的item会覆盖第一个dict的item。原创 2020-04-21 17:15:00 · 111 阅读 · 0 评论 -
在Shell直接运行Python命令并显示
python -c 'print("Hi")'Hi原创 2020-04-15 20:43:00 · 892 阅读 · 0 评论 -
Python新建文件夹(如果不存在)
import osif not os.path.exists(directory): os.mkdir(directory)原创 2019-12-30 23:44:00 · 175 阅读 · 0 评论 -
Python格式输出汇总
print ('%10s'%('test'))print ('{:<10}'.format('test'))#left-alignedprint ('{:>10}'.format('test'))#left-alignedprint ('{:10}'.format('test'))# defaut(right-aligned)print ('{:_<10}'.f...原创 2017-07-04 11:33:00 · 212 阅读 · 0 评论 -
Python的list中的选取范围
a = [1,2,3,4,5,6,7,8,9,10]a[0:1] = [1]a[0:2] = [1,2]包含开头,不包含结尾。a [:-1]: 从头一直到最后一个元素a[-1],但不包含最后一个元素。Python这样做的原因是:word[:2] # 取前两个word[2:] # 除了前两个,其他全部选取...原创 2017-07-02 22:37:00 · 901 阅读 · 0 评论 -
Python内部变量与外部变量
def outer(): x = 'outer x' def inner(): x = 'inner x' print(x) inner() print(x) # 这里的`x`与`x = 'outer x'`处在同一个Enclosingouter()运行结果:inner xouter x使用nonloc...原创 2017-06-19 20:26:00 · 253 阅读 · 0 评论 -
Python文件路径操作
print(os.environ.get('HOME')) # 打印`HOME`这个环境变量/Users/<>file_path = os.environ.get('HOME') + '/text.txt' # 拼贴文件路经,注意不要漏掉`/`print(file_path)/Users/<>/text.txtfile_path = os.p...原创 2017-06-15 09:35:00 · 113 阅读 · 0 评论 -
Python查看文件属性
import os print(os.stat('my_module.py'))输出:os.stat_result(st_mode=33188, st_ino=7348222, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=198, st_atime=1497418897, st_mtime=14974...原创 2017-06-14 22:37:00 · 211 阅读 · 0 评论 -
Python修改文件名
import osos.rename('original_name.txt','new_name.txt')原创 2017-06-14 22:32:00 · 135 阅读 · 0 评论 -
Python删除文件夹
import osos.rmdir('OS-Demo-2')os.removedirs('OS-Demo-3/sub-Dir-1') os.removedirs()会自动将上一级文件夹也删除,谨慎使用!原创 2017-06-14 17:28:00 · 77 阅读 · 0 评论 -
Python新建文件夹
import osos.mkdir('OS-Demo-2')os.makedirs('OS-Demo-3/sub-Dir-1') os.mkdir()和os.makedirs()都可以新建文件夹,区别在于,os.makedirs()能自动创建上一级文件夹,如果不存在的话。...原创 2017-06-14 17:24:00 · 114 阅读 · 0 评论 -
Python改变当前工作目录
import osprint(os.getcwd()) # 打印当前工作目录os.chdir('/Users/<username>/Desktop/') # 将当前工作目录改变为`/Users/<username>/Desktop/`以 list 的形式列出当前目录下的文件和目录print(os.listdir())...原创 2017-06-14 17:16:00 · 226 阅读 · 0 评论 -
Python中的try-finally
>>> try:... raise KeyboardInterrupt... finally:... print('Goodbye, world!')...Goodbye, world!KeyboardInterruptTraceback (most recent call last): File "<stdin>", li...原创 2017-06-10 22:13:00 · 83 阅读 · 0 评论 -
Python Class (一)
继承class Character(object): def __init__(self, name): self.health = 100 self.name = name def printName(self): print (self.name) class Blacksmith(Characte...原创 2017-06-13 22:06:00 · 61 阅读 · 0 评论 -
Python 调用自己编写的Class
假设自己写的 class 文件myPets.py放在当前目录的子目录/myClasses下,在myPets.py中定义了一个 class 叫Pet。现在要调用Pet这个 class :from myClasses.myPets import Petginger = Pet("Ginger", "Cat")myPets.py:class Pet(object):'''obje...原创 2017-06-12 12:21:00 · 314 阅读 · 0 评论 -
Python文件读写(一)
import time as tfrom os import pathdef createFile(dest): date = t.localtime(t.time()) name = '%d_%d_%d.txt' %(date[1],date[2],(date[0] %100)) # 2017 % 100 = 17 if not (path.isfile...原创 2017-06-11 20:38:00 · 129 阅读 · 0 评论 -
range类型(Python)
range 不是 iterator>>> R = range(3)>>> next(R)Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: 'range' object is not an iterato...原创 2017-06-11 17:08:00 · 119 阅读 · 0 评论 -
Zip函数(Python)
>>> z = zip((2,3,4),(33,44,55))>>> z<zip object at 0x1022cdb88>>>> list(z)[(2, 33), (3, 44), (4, 55)]要注意 ** zip 也是_one-pass iterator** !被遍历一次之后会自动_消失_。zip类...原创 2017-06-11 17:00:00 · 76 阅读 · 0 评论 -
enumerate()(Python)
>>> E=enumerate('spam')>>> E<enumerate object at 0x1021ceca8>>>> I=iter(E)>>> next(I)(0, 's')>>> next(I)(1, 'p')>>> list(enumer...原创 2017-06-11 15:32:00 · 65 阅读 · 0 评论 -
Python星号表达式提取数据
def drop_first_last(grades): first,*middle,last=grades return middle这段代码的作用是grades中的元素,第一个和最后一个分别被提取到first和last,而middle提取中间部分的所有其他元素。注意:drop_first_last(1,2,3,4)会报参数错误,正确的写法是drop_first_last...原创 2017-06-11 09:55:00 · 158 阅读 · 0 评论