CS231n:Python Numpy教程

  • Python

    • 基本数据类型
    • 容器
      • 列表
      • 字典
      • 集合
      • 元组
    • 函数  
  • Numpy
    • 数组  
    • 访问数组
    • 数据类型
    • 数组计算
    • 广播
  • SciPy
    • 图像操作
    • MATLAB文件
    • 点之间的距离
  • Matplotlib
    • 绘制图形
    • 绘制多个图形
    • 图像

Python


python实现的经典的quicksort算法

 1 def quicksort(arr):
 2     if len(arr)<=1:
 3         return arr
 4     pivot = arr[len(arr)/2]
 5     left = [x for x in arr if x < pivot]
 6     middle = [x for x in arr if x == pivot]
 7     right = [x for x in arr if x > pivot]
 8     return quicksort(left) + middle + quicksort(right)
 9
10 print quicksort([3,6,8,10,1,2,1])
11 #prints "[1,1,2,3,6,8,10]"

数字:整型和浮点型的使用与其他语言类似。

x = 3
print(type(x))#printd "<type ‘int‘>"
print(x) #prints "3"
print(x + 1) #Addition;prints "4"
print(x - 1) #Subtraction; prints "2"
print(x * 2) #Multiplication; prints "6"
print(x ** 2) #Expoentiaton; prints "9"
x += 1
print(x)# prints "4"
x *= 2
print(x) #prints "8"
y = 2.5
print(type(y))# prints "<type ‘float‘>"
print(y,y + 1,y * 2,y ** 2) #prints "2.5 3.5 5.0 6.25"

注意!!!! Python 中没有x++和x--的操作符。

布尔型:Python实现了所有的布尔逻辑。

t = True
f = False

print(type(t)) #prints "<type‘bool‘>"
print(t and f ) #logical AND; prints "False"
print(t or f )#Logical OR; prints "True"
print( not t )#Logical NOT; prints "False"
print(t != f) #Logical XOR;prints "True"

字符串

hello = ‘hello‘ #String literals  can use single quotes
world = ‘world‘ # pr double quotes; it does not matter,
print(hello) #prints "hello"
print(len(hello)) #String length; prints "5"
hw = hello + ‘ ‘+ world #String concatention
print(hw)# prints "hello world "
hw12 = ‘%s %s %d‘ % (hello,world,12) #sprintf style string formatting
print(hw12)#prints "hello world 12"

字符串对象的方法

s = "hello"
print(s.capitalize()) #Capitalize a string prints "hello"
print(s.upper()) #Convert a stirng to upercase; prints "HELLO"
print(s.rjust(7))#Righr-justify a string,padding with space; prints "  hello"
print(s.center(7))#Center a string,padding with space;prints " hello "
print(s.replace(‘l‘,‘(ell)‘)) #Replace all instance of one substring with another;
                                #prints "he(ell)(ell)o"
print(‘ world‘.strip())#Strip leading and trailing whitespace; prints "world"

容器 Containers

容器类型:列表(lists) 字典(dictionaries) 集合(sets)和元组(tuples)

列表Lists

列表就是python 中的数组,但是列表长度可变,且能包含不同类型元素

xs  = [3,1,2] #Create a list
print( xs ,xs[2]) #prints "[3,1,2] 2"
print(xs[-1]) #Negative indices count from the end of the list; prints "2"
xs[2] = ‘foo‘ #Lists can contain elements of different types
print(xs) #Prints "[3,1,‘foo‘]"
xs.append(‘bar‘)#Add a new element to the end of the list
print(xs) #prints
x = xs.pop()#Remove and return the last element of the list
print(x,xs)#Prints "bar [3,1,‘foo‘]"

切片Slicing : 为了一次性地获取列表中的元素,python 提供了一种简洁的语法,这就是切片。

nums = list(range(5)) #range is a built-in function that creates a list of integers
print(nums)#prints "[0,1,2,3,4]"
print(nums[2:4])#Get a slice from index 2 to 4 (exclusive); prints ‘[2,3]"
print(nums[2:])#Get a slice from index 2 to the end; prints "[2,3,4]"
print(nums[:2])#Get a slice from the start to index 2 (exclusive); prints "[0,1]"
print(nums[:])#Get a slice of the whole list ; prints "[0,1,2,3,4]"
print(nums[:-1])#Slice indices can be negative; prints "[0,1,2,3]"
nums[2:4] = [8,9]      # Assign a new sublist to a slice
print(nums)#prints "[0,1,8,9,4]"

在Numoy数组的内容中,再次看到切片语法。

循环LOOPS

animals =[‘cat‘,‘dog‘,‘monkey‘]
for animal in animals:
    print(animal)
#prints "cat", "dog","monkey",each on its own line.

如果想要在循环体内访问每个元素的指针,可以使用内置的enumerate函数

animals = [‘cat ‘,‘dog‘,‘monkey‘]
for idx,animal in enumerate(animals):
    print(‘#%d: %s‘%(idx + 1,animal))

#prints "#1: cat","#2: dog","#3: monkey",each on its own line

列表推导List comprehensions :在编程的时候,我们常常想要将一个数据类型转换为另一种。

将列表中的每个元素变成它的平方。

nums = [0,1,2,3,4]
squares = []
for x in nums:
    squares.append(x ** 2)
print(squares) #Prints [0,1,4,9,16]

使用列表推导:

nums  = [0,1,2,3,4]
squares = [x ** 2 for x in nums]
print(squares) # prints [0,1,4,9,16]

列表推导还可以包含条件:

nums = [0,1,2,3,4]
even_squares = [x ** 2 for x in nums if x % 2 == 0]
print(even_squares) # prints "[0,4,16]"

字典Dicionaries

字典用来存储(键,值)对,

d = {‘cat‘:‘cute‘,‘dog‘:‘furry‘}#Create a new dictionary with come data
print(d[‘cat‘]) #Get an entry from a dictionary ; prints "cute"
print(‘cat‘ in d) #Check if a dictionary has a given key; prints "Ture"
d[‘fish‘] = ‘wet‘ #Set an entry in a dictionary
print(d[‘fish‘]) # prints "wet"
# print d[‘monkey‘] #KeyError: ‘monkey ‘ not a key of d
print(d.get(‘monkey‘,‘N/A‘)) # Get an element with a default; prints "N/A"

print(d.get(‘fish‘,‘N/A‘))#Get an element with a default ; prints "wet"
del d[‘fish‘] #Remove an element from a dictionary
print(d.get(‘fish‘,‘N/A‘)) # "fish" is no longer a key ;prints "N/A"

循环LOOPS:在字典中,用键来迭代。

d = {‘person‘:2,‘cat‘:4,‘spider‘:8}
for animal in d:
    legs = d[animal]
    print(‘A %s has %d legs‘ % (animal,legs))
#Prints "A person has 2 legs", " A spider has 8 legs","A cat has 4 legs"

访问键和对应的值,使用items方法:

d = {‘person‘:2,‘cat‘:4,‘spider‘:8}
for animal,legs in d.items():
    print(‘A %s has %d legs‘ % (animal,legs))
#prints " A person has 2 legs","A spider has 8 legs","A cat has 4 legs"

字典推导Dictionary comprehensions :和列表推导类似,但是允许你方便地构建字典。

nums = {0,1,2,3,4}
even_num_square = {x:x**2 for x in nums if x % 2 == 0}
print(even_num_square) #  prints "{0:0,2:4,4:16}"

原文地址:https://www.cnblogs.com/Davirain/p/8460282.html

时间: 2024-08-01 13:39:28

CS231n:Python Numpy教程的相关文章

python numpy教程

python numpy教程 2014-08-10 22:21:56 分类: Python/Ruby 先决条件 在阅读这个教程之前,你多少需要知道点python.如果你想重新回忆下,请看看Python Tutorial. 如果你想要运行教程中的示例,你至少需要在你的电脑上安装了以下一些软件: Python NumPy 这些是可能对你有帮助的: ipython是一个净强化的交互Python Shell,对探索NumPy的特性非常方便. matplotlib将允许你绘图 Scipy在NumPy的基础

Python 机器学习库 NumPy 教程

0 Numpy简单介绍 Numpy是Python的一个科学计算的库,提供了矩阵运算的功能,其一般与Scipy.matplotlib一起使用.其实,list已经提供了类似于矩阵的表示形式,不过numpy为我们提供了更多的函数.如果接触过matlab.scilab,那么numpy很好入手. 1 安装 pip install numpy 在NumPy中,维度称之为axis(复数是axes),维度的数量称之为rank. (通用做法import numpu as np 简单输入) 2 多维数组 NumPy

Python 快速教程(补充篇04): Python简史

Python的起源 Python的作者,Guido von Rossum,确实是荷兰人.1982年,Guido从阿姆斯特丹大学(University of Amsterdam)获得了数学和计算机硕士学位.然而,尽管他算得上是一位数学家,但他更加享受计算机带来的乐趣.用他的话说,尽管拥有数学和计算机双料资质,他总趋向于做计算机相关的工作,并热衷于做任何和编程相关的活儿. Guido von Rossum 在那个时候,他接触并使用过诸如Pascal.C. Fortran等语言.这些语言的基本设计原则

numpy教程:数组操作

http://blog.csdn.net/pipisorry/article/details/39496831 Array manipulation routines numpy数组基本操作,包括copy, shape, 转换(类型转换), type, 重塑等等.这些操作应该都可以使用numpy.fun(array)或者array.fun()来调用. Basic operations copyto(dst, src[, casting, where])Copies values from one

windows上安装Anaconda和python的教程详解

一提到数字图像处理编程,可能大多数人就会想到matlab,但matlab也有自身的缺点: 1.不开源,价格贵 2.软件容量大.一般3G以上,高版本甚至达5G以上. 3.只能做研究,不易转化成软件. 因此,我们这里使用Python这个脚本语言来进行数字图像处理. 要使用Python,必须先安装python,一般是2.7版本以上,不管是在windows系统,还是Linux系统,安装都是非常简单的. 要使用python进行各种开发和科学计算,还需要安装对应的包.这和matlab非常相似,只是matla

给深度学习入门者的Python快速教程

基础篇 numpy和Matplotlib篇 本篇部分代码的下载地址: https://github.com/frombeijingwithlove/dlcv_for_beginners/tree/master/chap5 5.3 Python的科学计算包 – Numpy numpy(Numerical Python extensions)是一个第三方的Python包,用于科学计算.这个库的前身是1995年就开始开发的一个用于数组运算的库.经过了长时间的发展,基本上成了绝大部分Python科学计算

《Python编程从入门到实践》+《流畅的Python》+《Python基础教程(第3版)》分析对比

<Python编程从入门到实践>针对所有层次的Python 读者而作的Python 入门书.全书分两部分:第一部分介绍用Python 编程所必须了解的基本概念,包括matplotlib.NumPy 和Pygal 等强大的Python 库和工具介绍,以及列表.字典.if 语句.类.文件与异常.代码测试等内容:第二部分将理论付诸实践,讲解如何开发三个项目,包括简单的Python 2D 游戏开发如何利用数据生成交互式的信息图,以及创建和定制简单的Web 应用,并帮读者解决常见编程问题和困惑. <

Python学习教程(Python学习路线+Python学习视频):Python数据结构

Python学习教程(Python学习路线+Python学习视频):Python数据结构   数据结构引言:   数据结构是组织数据的方式,以便能够更好的存储和获取数据.数据结构定义数据之间的关系和对这些数据的操作方式.数据结构屏蔽了数据存储和操作的细节,让程序员能更好的处理业务逻辑,同时拥有快速的数据存储和获取方式. 在这篇文章中,你将了解到多种数据结构以及这些数据结构在Python中实现的方式.    抽象数据类型和数据结构 数据结构是抽象数据类型(ADT)的实现,通常,是通过编程语言提供的

Python学习教程:最全Python110道面试题!面试你肯定用得上!

Python学习教程(Python学习路线):最全Python面试题! 为了大家更好的消化,这里分成几次给大家出题目和教程! 1.一行代码实现1--100之和 利用sum()函数求和 2.如何在一个函数内部修改全局变量 函数内部global声明 修改全局变量 3.列出5个python标准库 os:提供了不少与操作系统相关联的函数 sys: 通常用于命令行参数 re: 正则匹配 math: 数学运算 datetime:处理日期时间 4.字典如何删除键和合并两个字典 del和update方法 5.谈