[译] Python Numpy学习资料 (1)

原文来自http://cs231n.github.io/python-numpy-tutorial/#python-containers

Python本身是一种通用的编程语言,在一些常用库的帮助下(如numpy、scipy、matplotlib),Python成为了可用于科学计算的强大环境。
大部分读者可能已经有一些关于Python和numpy的经验,对于另一部分不熟悉的读者,该章节可作为Python编程语言及其在科学计算的应用的速成课程。

**

Python

**
Phython是一种高级动态多模式编程语言,Phython的代码很像伪代码,能够用少量语言表达强大的观点,同时可读性好。比如下面就是经典的快速排序算法:

def quicksort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quicksort(left) + middle + quicksort(right)

print(quicksort([3,6,8,10,1,2,1])) # 输出 "[1, 1, 2, 3, 6, 8, 10]"

Python版本

2种版本的Python, 2.7和3.5,但两种互不兼容。本课程使用3.5。
在command line中运行 python–version可检查版本。

基本数据类型

像大多数语言一样,Python的数据类型包括integers, floats, booleans和strings。
Numbers数字: Integers和floats和大多数语言的用法一样。

x = 3
print(type(x)) # 输出"<class 'int'>"
print(x)       # 输出"3"
print(x + 1)   # 加; 输出"4"
print(x - 1)   # 减; 输出"2"
print(x * 2)   # 乘; 输出"6"
print(x ** 2)  # 幂; 输出"9"
x += 1
print(x)  # 输出 "4"
x *= 2
print(x)  # 输出 "8"
y = 2.5
print(type(y)) # 输出 "<class 'float'>"
print(y, y + 1, y * 2, y ** 2) # 输出 "2.5 3.5 5.0 6.25"

注意,Python没有递增和递减运算符 (x++,x–) 。
对于复杂数字,Python也有一些内置类型。

Booleans: Python能进行所有的Boolean逻辑运算,但是用英文单词而不是符号 (&&, ||, etc.):

t = True
f = False
print(type(t)) # 输出 "<class 'bool'>"
print(t and f) # Logical AND; 输出 "False"
print(t or f)  # Logical OR; 输出 "True"
print(not t)   # Logical NOT; 输出 "False"
print(t != f)  # Logical XOR; 输出 "True" 异或

Strings: Python对strings的支持性很好:

hello = 'hello'    # 字符串文字可用单引号,也可用双引号,没有关系
world = "world"    
print(hello)       # 输出 "hello"
print(len(hello))  # 字符串长度; 输出 "5"
hw = hello + ' ' + world  # 字符串连接
print(hw)  # 输出 "hello world"
hw12 = '%s %s %d' % (hello, world, 12)  # sprintf style string formatting
print(hw12)  # 输出 "hello world 12"

String objects(字符串对象) 有许多methods:

s = "hello"
print(s.capitalize())  # 将字符串首字母大写; 输出 "Hello"
print(s.upper())       # 转换为全部大写; 输出 "HELLO"
print(s.rjust(7))      # 靠右对齐,用空格填充; 输出 "  hello"
print(s.center(7))     # 居中,用空格填充; 输出 " hello "
print(s.replace('l', '(ell)'))  # 替换相应子字符串;
                                # 输出 "he(ell)(ell)o"
print('  world '.strip())  # 去除前面和后面的空格; 输出 "world"

Containers

几种内置container类型: lists, dictionaries, sets, tuples(多元组)。

Lists

Python中的list相当于一个array(数组), 但是大小可调,而且能包含不同类型的元素。

xs = [3, 1, 2]    # 创建一个list
print(xs, xs[2])  # 输出 "[3, 1, 2] 2"
print(xs[-1])     # 负数指号表示从list的结尾倒数; 输出 "2"
xs[2] = 'foo'     # Lists可包含不同种类的元素
print(xs)         # 输出 "[3, 1, 'foo']"
xs.append('bar')  # 在list结尾添加一个新的元素
print(xs)         # 输出 "[3, 1, 'foo', 'bar']"
x = xs.pop()      # 返回list中的最后一个元素
print(x, xs)      # 输出 "bar [3, 1, 'foo']"

Slicing: 不仅能一次访问一个list元素, Python提供了访问sublists的简明语法; 称为slicing:

nums = list(range(5))     # range是一个内置函数,创建一个整数的list
print(nums)               # 输出 "[0, 1, 2, 3, 4]"
print(nums[2:4])          # 索引从2到4(不包含4)的slice; 输出 "[2, 3]"
print(nums[2:])           # 索引为2到结尾的slice; 输出 "[2, 3, 4]"
print(nums[:2])           # 从开头到索引为2 (不包含2)的slice; 输出 "[0, 1]"
print(nums[:])            # 整个list的slice; 输出 "[0, 1, 2, 3, 4]"
print(nums[:-1])          # Slice的指号可以是负数; 输出 "[0, 1, 2, 3]"
nums[2:4] = [8, 9]        # 给一个slice指定新的sublist 
print(nums)               # 输出 "[0, 1, 8, 9, 4]"

Loops: 可以如下循环遍历list:

animals = ['cat', 'dog', 'monkey']
for animal in animals:
    print(animal) # 输出 "cat", "dog", "monkey", 每行一个.

如果你想要接触到loop里面每个元素的index,采用内置enumerate 函数:

animals = ['cat', 'dog', 'monkey']
for idx, animal in enumerate(animals):
    print('#%d: %s' % (idx + 1, animal)) # 输出 "#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)   # 输出 [0, 1, 4, 9, 16]

用list comprehension代码会更简单:

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

List comprehensions也可以包含条件性:

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

Dictionaries

dictionary 存储 (key, value)成对的数据, 类似Java中的 Map或者Javascript中的object,可以这样用:

d = {'cat': 'cute', 'dog': 'furry'}  # 创建一个新的dictionary,其中‘cat’是key, ‘cute’是value
print(d['cat'])       # 得到dictionary的入口; 输出 "cute"
print('cat' in d)     # 检查一个dictionary是否由a given key; 输出 "True"
d['fish'] = 'wet'     # 在一个dictionary中设定一个入口
print(d['fish'])      # 输出 "wet" 
print(d['monkey'])    # KeyError: 'monkey' not a key of d
print(d.get('monkey', 'N/A'))  #得到默认元素; 输出 "N/A"(没有)
print(d.get('fish', 'N/A'))    #得到默认元素; 输出 "wet"
del d['fish']         # 从dictionary中去除一个元素
print(d.get('fish', 'N/A')) # "fish"不再是一个key; 输出 "N/A"

Loops: 迭代dictionary中的key:

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

访问全部的keys和它们对应的values, 使用 items 方法:

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

Dictionary comprehensions: 类似list comprehensions, 但是可以让你轻松创建dictionaries:

nums = [0, 1, 2, 3, 4]
even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
print(even_num_to_square)  # 输出 "{0: 0, 2: 4, 4: 16}"

Sets

A set是不同元素的无序集合。比如:

animals = {'cat', 'dog'}
print('cat' in animals)   # 检查元素是否在set内; 输出 "True"
print('fish' in animals)  # 输出 "False"
animals.add('fish')       # 向set中添加一个元素
print('fish' in animals)  # 输出 "True"
print(len(animals))       # set中元素的个数; 输出 "3"
animals.add('cat')        # 向set中添加已有元素,set不会改变
print(len(animals))       # 输出 "3"
animals.remove('cat')     # 去除一个元素
print(len(animals))       # 输出 "2"

Loops: 在set中遍历迭代和在list中遍历迭代的语法相同;但是鉴于set是无序的,不能期待你访问set中元素的顺序。

animals = {'cat', 'dog', 'fish'}
for idx, animal in enumerate(animals):
    print('#%d: %s' % (idx + 1, animal)) # 输出 "#1: fish", "#2: dog", "#3: cat"

Set comprehensions: 类似lists和dictionaries,我们可以轻松用set comprehensions构造sets:

from math import sqrt
nums = {int(sqrt(x)) for x in range(30)}
print(nums)  # 输出 "{0, 1, 2, 3, 4, 5}"
Tuples(元组)

Tuple 是一系列值的固定有序列表。Tuple在许多方面类似list; 最重要的区别之一是tuples可用作dictionaries里的keys、sets中的元素, 但是lists不能。比如:

d = {(x, x + 1): x for x in range(10)}  # 用tuple keys创建dictionary
t = (5, 6)        # 创建tuple
print(type(t))    # 输出 "<class 'tuple'>"
print(d[t])       # 输出 "5"
print(d[(1, 2)])  # 输出 "1"

Functions

Python的函数由def 关键字定义。比如:

def sign(x):
    if x > 0:
        return 'positive'
    elif x < 0:
        return 'negative'
    else:
        return 'zero'

for x in [-1, 0, 1]:
    print(sign(x)) # 输出 "negative", "zero", "positive"

我们用可选的关键词参数来定义函数:

def hello(name, loud=False):
    if loud:
        print('HELLO, %s!' % name.upper())
    else:
        print('Hello, %s' % name)

hello('Bob') # 输出 "Hello, Bob"
hello('Fred', loud=True)  # 输出 "HELLO, FRED!"

Classes

定义classes的语法是直接的:

class Greeter(object):

    # Constructor
    def __init__(self, name):
        self.name = name  # Create an instance variable

    # Instance method
    def greet(self, loud=False):
        if loud:
            print('HELLO, %s!' % self.name.upper())
        else:
            print('Hello, %s' % self.name)

g = Greeter('Fred')  # Construct an instance of the Greeter class
g.greet()            # Call an instance method; 输出 "Hello, Fred"
g.greet(loud=True)   # Call an instance method; 输出 "HELLO, FRED!"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值