Scipy Lecture Notes学习笔记(一)Getting started with Python for science 1.2. The Python language
Scipy Lecture Notes学习笔记(一)Getting started with Python for science
1.2. The Python language
1.2.2. 基本类型
1.2.2.1. Numerical types
复数
a = 1.5 + 0.5j
type(1. + 0j)
print(a.real) print(a.imag)
幂运算
print(2**10)
print(3**3)
类型转换
float(1)
注意:在python3中,虽然3跟2是int型,但是计算后得到的是float型结果,如果想要得到相除后的整数部分,直接采用下面
1.2.2.2. Containers
python提供的很多可以存放对象的结构,称之为containers,主要有lists,strings,dictionaries,tuples,sets
list:链表,有序的项目, 通过索引进行查找,使用方括号”[]”;
tuple:元组,元组将多样的对象集合到一起,不能修改,通过索引进行查找, 使用括号”()”,但可以对一个tuple重新赋值,tuple的存在可能基于两个原因:1)在python中,它比list操作速度更快,如果我们定义一个常量集,不需要修改,只需要遍历,则最好用tuple;2)安全性:由于tuple不能进行修改,那么对于这种类型的数据,tuple可以避免数据被偶然修改。;
dict:字典,字典是一组键(key)和值(value)的组合,通过键(key)进行查找,没有顺序, 使用大括号”{}”;
set:集合,无序,元素只出现一次, 自动去重,使用”set([])”
应用场景:
list, 简单的数据集合,可以使用索引;
tuple, 把一些数据当做一个整体去使用,不能修改;
dict,使用键值和值进行关联的数据;
set,数据只出现一次,只关心数据是否出现, 不关心其位置;
Lists:可变对象
colors = ['red', 'blue', 'green', 'black', 'whiteprint(colors[0])print(colors[1]) print(colors[2]) print(colors[3]) print(colors[-1]) print(colors[-2]) print(colors[2:3]) #lists中[开始位置:结束位置]开始位置是按照0,1,2,3,标号,结束位置就是物理意义上面的个数,从标号i#开始,到第j个元素结束,因此color[2:3]就是一个元素,标号为2,个数是第三个的green,但是此时的green是lists print(colors[0:-1]) print(colors[0:5:2]) #[开始位置:结束位置:步长],注意比较两者结果的不同,开始位置按标号技术,结束位置按照物理个数计数 print(colors[0:4:2]) #[开始位置:结束位置:步长] print(type(colors[0])) print(type(colors[2:3]))
输出:red blue green black white black ['green'] ['red', 'blue', 'green', 'black'] ['red', 'green', 'white'] ['red', 'green'] <class 'str'> <class 'list'>
注意,colors[2]的类型是string,而colors[2:3]的类型是list
倒置reverse
指令:colors.reverse()
输入:
colors = ['red', 'blue', 'green', 'black', 'white'] rcolors = colors[::-1] rcolors1 = colors rcolors1.reverse() print(colors) print(rcolors) print(rcolors1)
输出:
['white', 'black', 'green', 'blue', 'red'] ['white', 'black', 'green', 'blue', 'red'] ['white', 'black', 'green', 'blue', 'red']
输入:
colors = ['red', 'blue', 'green', 'black', 'white'] rcolors = colors[::-1] rcolors2 = colors.copy() rcolors2.reverse() print(colors) print(rcolors) print(rcolors2)
输出:
['red', 'blue', 'green', 'black', 'white'] ['white', 'black', 'green', 'blue', 'red'] ['white', 'black', 'green', 'blue', 'red']
注意上下两段代码的区别,“=” 是两个变量共同分享一段内存,对新的变量赋值同时会影响原来的变量,因此正确的做法应该是b=a.copy()
输入:
rcolors + colors
输出:
['white','black','green','blue','red','white', 'black', 'green', 'blue', 'red']
排序sort
输入:
print(rcolors) print(sorted(rcolors)) print(colors) colors.sort() print(colors)
输出:
['white', 'black', 'green', 'blue', 'red'] ['black', 'blue', 'green', 'red', 'white'] ['red', 'blue', 'green', 'black', 'white'] ['black', 'blue', 'green', 'red', 'white']
字符串String:字符串是不可变的对象,不可能修改其内容。然而,人们可能会从原来的创建新的字符串。
输入:
a = "hello, world!" print(a[3:6]) #标号也是从0开始计数,到标号为3的元素,截至是物理位置第6个元素 print(a[2:10:2]) print(a[::3]) print("oraginal value=",a) print(a.replace('l', 'z', 1)) #采用replace指令对元素值进行替换 print("new value=",a) #但是原来的string变量并没有发生改变
输出:
lo, lo o hl r! oraginal value= hello, world! hezlo, world! new value= hello, world!
格式设置:
输入:
'An integer: %i; a float: %f; another string: %s' % (1, 0.1, 'string')
输出:
'An integer: 1; a float: 0.100000; another string: string'
输入:
i = 102 filename = 'processing_of_dataset_%d.txt' % i filename
输出:
'processing_of_dataset_102.txt'
字典Dictionaries:一个将键映射到值的高效表。它的英文一个无序的容器,他可以方便的存储于检索与名称相关的值
输入
tel = {'emmanuelle': 5752, 'sebastian': 5578} tel['francis'] = 5915 print(tel)
输出:
{'emmanuelle': 5752, 'sebastian': 5578, 'francis': 5915}
Tuples:元组,不可变
输入: t = 12345, 54321, 'hello!' t[0] 输出: 12345
Sets集合
输入:
s = set(('a', 'b', 'c', 'a')) print(s) print(s.difference('a','b')) print(s)
输出:
{'c', 'b', 'a'} {'c'} {'c', 'b', 'a'}
1.2.3 控制流程
1.2.3.2. for/range
输入:
for i in range(4):print(i)
输出:
0 1 2 3
输入:
for word in ('cool', 'powerful', 'readable'):print('Python is %s' % word)
输出:
Python is cool Python is powerful Python is readable
1.2.3.3. while/break/continue
break:终止循环语句跳出整个循环,continue,跳出本次循环,进行下一轮循环
输入:
z = 1 + 1jwhile abs(z) < 100:if z.imag == 0:breakz = z**2 + 1 print(z)z = 1 + 1jwhile abs(z) < 100:if z.imag == 1: break z = z**2 + 1 print(z) z = 1 + 1j while abs(z) < 100: if z.imag == 0: continue z = z**2 + 1 print(z) a = [1, 0, 2, 4] for element in a: if element == 0: continue print(1. / element)
输出:
(-134+352j) (1+1j) (-134+352j) 1.0 0.5 0.25
输入:
message = "Hello how are you?" message.split() # returns a list print(message) #再次说明,message作为string型,是不可变的 print(message.split()) #而message.split()返回的是一个list结构 for word in message.split():print(word)
输出:
Hello how are you? ['Hello', 'how', 'are', 'you?'] Hello how are you?
输入
words = ('cool', 'powerful', 'readable') for index, item in enumerate(words):#enumerate是python内置函数print((index, item))
输出:
(0, 'cool') (1, 'powerful') (2, 'readable')
Looping over a dictionary:The ordering of a dictionary in random, thus we use sorted()
which will sort on the keys.
输入:
d = {'a': 1, 'b':1.2, 'c':1j}for key, val in sorted(d.items()):print('Key: %s has value: %s' % (key, val))
输出:
Key: a has value: 1 Key: b has value: 1.2 Key: c has value: 1j
exercise
Compute the decimals of Pi using the Wallis formula:
输入:
def wallis(n):
pi = 2.
for i in range(1, n):
left = (2. * i)/(2. * i - 1.)
right = (2. * i)/(2. * i + 1.)
pi = pi * left * right #连乘
return pi
wallis(100000)
输出:
3.1415847995783834
1.2.4. Defining functions
输入:
def slicer(seq, start=None, stop=None, step=None): #seq是位置参数,start是可变参数,如果没有指定start,stop,step的值那么就取函数定义时的默认值,但是如果没有指定seq,那么函数则会报错return seq[start:stop:step] rhyme = 'one fish, two fish, red fish, blue fish'.split() #如果此时用的是双引号,那么rhyme类型变成string print(type(rhyme)) print(slicer(rhyme)) print(slicer(rhyme,step=2)) print(slicer(rhyme,start=1,stop=4,step=2))
输出:
<class 'list'> ['one', 'fish,', 'two', 'fish,', 'red', 'fish,', 'blue', 'fish'] ['one', 'two', 'red', 'blue'] ['fish,', 'fish,']
输入:如果不指定函数的位置参数seq,那么则会报错,函数缺少位置参数
slicer()
输出:
TypeError Traceback (most recent call last) <ipython-input-8-3c8febe6fdb8> in <module>() ----> 1 slicer()TypeError: slicer() missing 1 required positional argument: 'seq'
1.2.4.6 可变数量的参数
- 特殊形式的参数:
-
*args
:将任意数量的位置参数打包到一个元组中**kwargs
:将任意数量的关键字参数打包到字典中
输入
def variable_args(*args, **kwargs):print ('args is', args)print ('kwargs is', kwargs) variable_args('one', 'two', x=1, y=2, z=3) #前两个没有指定默认值,是位置参数,后面两个有默认值,是关键字参数
输出
args is ('one', 'two') kwargs is {'x': 1, 'y': 2, 'z': 3}
exercise: Fibonacci sequence
Write a function that displays the
n
first terms of the Fibonacci sequence, defined by:输入:
def Fibonacci(n):u=list(range(0,n))for i in range(2,n):u[0]=0;u[1]=1;u[i]=u[i-1]+u[i-2]; return u
Fibonacci(6)
输出:
[0, 1, 1, 2, 3, 5]
别人写的参考,似乎有点问题
输入:
def fib(n):"""Display the n first terms of Fibonacci sequence"""a, b = 0, 1i = 0while i < n:print(b)a, b = b, a+bi +=1fib(6)
输出:
1 1 2 3 5 8
Exercise: Quicksort
关键:
qsort(less_than) + [pivot] + qsort(greater_equal)
Implement the quicksort algorithm, as defined by wikipedia
伪代码: function quicksort(array)var list less, greaterif length(array) < 2return arrayselect and remove a pivot value pivot from arrayfor each x in arrayif x < pivot + 1 then append x to less else append x to greater return concatenate(quicksort(less), pivot, quicksort(greater))
函数定def qsort(lst):
""" Quick sort: returns a sorted copy of the list."""if len(lst) <= 1:return lstpivot, rest = lst[0], lst[1:]# Could use list comprehension:# less_than = [ lt for lt in rest if lt < pivot ] less_than = [] for lt in rest: if lt < pivot: less_than.append(lt) # Could use list comprehension: # greater_equal = [ ge for ge in rest if ge >= pivot ] greater_equal = [] for ge in rest: if ge >= pivot: greater_equal.append(ge) return qsort(less_than) + [pivot] + qsort(greater_equal) #理解快速排序,任意数组,将其第一个元素定为pivot,然后将数组分为两个部分,pivot和数组#剩余部分rest,将剩余部分与pivot作对比,将rest分为两个部分,大于等于pivot的元素,放#在greater_quanl中,比pivot小的元素放在less_than中,然后同样对得到的两个新的序列进#行上述操作,知道最后数组的长度为1,完成所有排序
调用:
lst=[9,4,5,6] qsort(lst)
1.2.5.2. Importing objects from modules
输入:
import os os print(os.listdir('.'))
输出:
['.idea', '.ipynb_checkpoints', 'BoardingPass_MyNameOnInSight.png', 'Industry AI tianchi', 'kaggle-quora-question-pairs-master.zip', 'mobike', 't.xlsx', 'Thumbs.db', 'UAI算法比赛', 'Untitled.ipynb', 'Untitled1.ipynb', 'Untitled2.ipynb', 'Untitled3.ipynb', '人工胰腺', '天池资料', '数据挖掘比赛入门_以去年阿里天猫推荐比赛为例.docx', '新手入门四课时.zip']
输入:
os.remove("x.xlsx") os.listdir('.')
输出:
['.idea','.ipynb_checkpoints','BoardingPass_MyNameOnInSight.png','Industry AI tianchi','kaggle-quora-question-pairs-master.zip','mobike', 't.xlsx', 'Thumbs.db', 'UAI算法比赛', 'Untitled.ipynb', 'Untitled1.ipynb', 'Untitled2.ipynb', 'Untitled3.ipynb', 'x.xlsx', '人工胰腺', '天池资料', '数据挖掘比赛入门_以去年阿里天猫推荐比赛为例.docx', '新手入门四课时.zip']
1.2.5.3. Creating modules
创建模块demo2.py,其文件内容如下
def print_b():"Prints b."print 'b'def print_a():"Prints a."print 'a'# print_b() runs on import print_b()if __name__ == '__main__': # print_a() is only executed when the module is run directly. print_a()
其中的 if __name__ == '__main__' 这一语句可以这样理解
通俗的理解
__name__ == '__main__'
:假如你叫小明.py,在朋友眼中,你是小明(__name__ == '小明')
;在你自己眼中,你是你自己(__name__ == '__main__')
。if __name__ == '__main__'
的意思是:当.py文件被直接运行时,if __name__ == '__main__'
之下的代码块将被运行;当.py文件以模块形式被导入时,if __name__ == '__main__'
之下的代码块不被运行demo2.py中定义了两个函数,如果想在别的文件中调用这两个函数,那么执行如下命令
from demo2 import print_a, print_b #从自定义的模块的demo2中调用print_a和print_b两个函数 print_a() print_b()
输出:
a b
1.2.7.1.
os
module: operating system functionality输入:
import os print(os.getcwd()) #获取当前路径 print(os.listdir(os.curdir))#列举当前路径下所有存在文件 os.mkdir('junkdir') #创建新的路径目录 print(os.listdir(os.curdir)) os.rename('junkdir', 'foodir')#将路径目录重命名 print(os.listdir(os.curdir)) os.rmdir('foodir') #删除新的路径 print(os.listdir(os.curdir))
输出:
D:\emmmmmm\test ['.ipynb_checkpoints', 'Untitled.ipynb'] ['.ipynb_checkpoints', 'junkdir', 'Untitled.ipynb'] ['.ipynb_checkpoints', 'foodir', 'Untitled.ipynb'] ['.ipynb_checkpoints', 'Untitled.ipynb']
转载于:https://www.cnblogs.com/huanjing/p/8624456.html
Scipy Lecture Notes学习笔记(一)Getting started with Python for science 1.2. The Python language相关推荐
- CEM计算电磁学 -- Lecture 2 学习笔记 (1) ---TMM 传输矩阵法(1)
目录 一.电磁场中的一维结构 二.传递矩阵法 1.模型结构 2.4×4矩阵方法(需要sort) (1)前提内容 (2)4×4矩阵方程式(用于求解电磁场方程) (3)LHI 情况下的解 (4)计算传输矩 ...
- python dict遍历_Python学习笔记:19个pythonic编程习惯,让你的Python入门更优雅
Python最大的优点之一就是语法简洁,好的代码就像伪代码一样,干净.整洁.一目了然. 要写出 Pythonic(优雅的.地道的.整洁的)代码,需要多看多学大牛们写的代码,github 上有很多非常优 ...
- Android Studio Notes/学习笔记
学习视频来源:https://www.bilibili.com/video/BV1jW411375J?from=search&seid=16068849106535436916 文章目录 小知 ...
- CEM计算电磁学 -- Lecture 1 学习笔记 (2) --- 极化、反射、透射
目录 一.电磁波的极化 1.线性极化(LP) 2.圆极化(CP) 3.两者的关系 4.以更清晰的方式进行表示 5.TE和TM极化 二.反射与透射 1.TE.TM波的反射.透射系数 2.反射.透射效率 ...
- 《机器学习》 周志华学习笔记第十四章 概率图模型(课后习题)python实现
一.基本内容 1.隐马尔可夫模型 1.1. 假定所有关心的变量集合为Y,可观测变量集合为O,其他变量集合为R, 生成式模型考虑联合分布P(Y,R,O),判别式模型考虑条件分布P(Y,R|O),给定一组 ...
- Python全栈学习笔记day 40.5+:线程池和线程池的Python标准模块--concurrent.futures
Python标准模块--concurrent.futures 源码:https://docs.python.org/dev/library/concurrent.futures.html #1 介绍: ...
- Python爬虫学习笔记_DAY_23_Python爬虫之bs4解析的基本使用介绍【Python爬虫】
目录 I.bs4的介绍 II.bs4的安装 III.bs4的基本语法使用 p.s.高产量博主,点个关注
- CS224N课程学习笔记
CS224N Lecture One学习笔记 本文是斯坦福大学CS224N课程(课程主页:http://web.stanford.edu/class/cs224n/) lecture one的学习笔记 ...
- [python教程入门学习]python学习笔记(CMD执行文件并传入参数)
本文章向大家介绍python学习笔记(CMD执行文件并传入参数),主要包括python学习笔记(CMD执行文件并传入参数)使用实例.应用技巧.基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋 ...
最新文章
- 程序员创业前要做哪些准备?
- 新手探索NLP(四)
- Dubbo 一篇文章就够了:Dubbo遇到初恋
- 全实践!3天物联网安全课程不断电
- 在乌班图中将py3设置为默认解释器
- 武汉游记,三件新鲜奇葩事
- Linux下编译FFMpeg
- skyline point解析
- 制作windows7系统的U盘启动盘
- 只知道人工智能远远不够 下一件大事将是边缘计算!
- matlab2020面板介绍
- linux 下查看硬盘容量
- STM32 之 HAL库
- 七日之都账号服务器,永远的7日之都开服时间一览表 7日之都最新服务器开服时间一览...
- 深入学习理解java虚拟机--1.win10 下构建64位 openJDK8
- 关于纯前端excel上传、下载功能
- windows无法连接到打印机?三个方法连接打印机(Win10系统)
- 安装系统时,硬盘格式转换
- 如何为你的网站添加二级域名?
- Google Play图标上传规则调整
热门文章
- linux uvc 支持的设备,摄像头是否支持uvc
- flex布局常用属性
- mysql 设置表空间位置_如何修改表空间数据文件路径
- 和与余数的和同余理解_5 同余 ——数论入门知识讲解系列
- python web flask开发框架_Python Web 开发框架,Flask 与 Django那个更好
- 智慧农场基本情况交流会议记录
- 通过mem函数在MicroPython中访问模块寄存器
- 2021年春季学期-信号与系统-第十三次作业参考答案-第四小题
- 关于举办第十六届全国大学生 智能汽车竞赛的通知
- 北京科技大学天津学院第三届智能车校内赛总决赛完美落幕