轉Python & Numpy 教程(上)

該教程來自於 Justin Johnson

我們將會使用Python編程語言來完成本課程(斯坦福大學cs231n)的所有作業。Python是一個偉大的通用編程語言,在一些流行庫(numpy,scipy,matplotlib)的幫助下,它可以提供一個科學計算的強大環境。

我們希望你們之中的大多數人已經有了使用Python和numpy的經驗;其餘的人,這個部分將作爲一個速成課程,幫助你們掌握Python編程語言,並且使用Python來做科學計算。

也許有些人有過matlab的使用經驗,所以我們也推薦numpyfor matlab user。

你還可以找到 IPythonnotebook version of this tutorial here。

Python

Python是一個高級、動態類型多範性編程語言。Python與僞代碼很相似,它允許你使用非常少的代碼來表達強大的思想。舉個例子,下面是一個經典的快速排序算法的Python實現:

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])
# Prints "[1, 1, 2, 3, 6, 8, 10]"

Python版本

目前有兩種不同的Python支持版本——Python 2.7和Python 3.4。Python 3.0引入了很多向後不兼容的變化,所以使用2.7編寫的代碼在3.4下可能無法正常工作,反之亦然。這門課程使用的是Python 2.7。

你可以通過在命令行運行 python --version 來查看Python版本。

Basic data types

與其他語言類似,Python有很多基本的數據類型,包括整型、浮點型、布爾型、字符串型。這些類型的表現與在其他編程語言中類似。

Numbers:整數和浮點數與其他語言中類似:

x = 3
print type(x) # Prints "<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  # Exponentiation; 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也有內置的長整型和複雜數類型,你可以在相關文檔中找到。

Booleans:Python實現所有的布爾邏輯通用操作,但是它不使用符號(&&,II,etc),而是使用英文單詞:

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"

Strings:Python對字符串支持很好:


hello = 'hello'   # String literals can use single quotes
world = "world"   # or double quotes; it does not matter.
print hello       # Prints "hello"
print len(hello)  # String length; prints "5"
hw = hello + ' ' + world  # String concatenation
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 string to uppercase; prints "HELLO"
print s.rjust(7)      # Right-justify a string, padding with spaces; prints "  hello"
print s.center(7)     # Center a string, padding with spaces; prints " hello "
print s.replace('l', '(ell)')  # Replace all instances of one substring with another;
                               # prints "he(ell)(ell)o"
print '  world '.strip()  # Strip leading and trailing whitespace; prints "world"

你可以在相關文檔中找到string方法的列表。

Containers

Python包含一些內置的容器類型:lists(列表),dictionaries(字典), sets(集合), and tuples(元組)。

Lists

list是數組在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 "[3, 1, 'foo', 'bar']"
x = xs.pop()     # Remove and return the last element of the list
print x, xs      # Prints "bar [3, 1, 'foo']"


實際上,你可以在官網文檔中找到更多的關於lists的細節。

Slicing:除了可以每次訪問列表的一個元素,Python提供了簡潔的語法來訪問子列表;這就叫做slicing:

nums = 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]"

我們還會在numpy arrays上下文中看到slicing。

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]

list comprehensions 也可以包含條件:

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]"

Dictionaries

一個字典存儲了(key,value)對,這與Java中的Map或者Javascript中的object都很相似。你可以這樣使用字典:

d = {'cat': 'cute', 'dog': 'furry'}  # Create a new dictionary with some 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 "True"
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:很容易對字典中的keys進行迭代:

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"

如果想要訪問keys和對應的values,可以使用iteritems 方法:

d = {'person': 2, 'cat': 4, 'spider': 8}
for animal, legs in d.iteritems():
    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:這與list comprehensions是相似的,但是允許你方便地構建字典。例如:

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  # Prints "{0: 0, 2: 4, 4: 16}"

Sets

Set是不同元素的無序集合。下面是一個簡單的例子:

animals = {'cat', 'dog'}
print 'cat' in animals   # Check if an element is in a set; prints "True"
print 'fish' in animals  # prints "False"
animals.add('fish')      # Add an element to a set
print 'fish' in animals  # Prints "True"
print len(animals)       # Number of elements in a set; prints "3"
animals.add('cat')       # Adding an element that is already in the set does nothing
print len(animals)       # Prints "3"
animals.remove('cat')    # Remove an element from a set
print len(animals)       # Prints "2"

通常,你想要知道的所有關於sets的東西可以在官方文檔中找到。

Loops:set中的迭代與list中具有相同的語法;然而,由於sets是無序的,你不能對訪問set中元素的順序做出假設:

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

Set comprehensions:與dictionaries和lists類似,我們可以很容易地使用set comprehensions來構建sets:

from math import sqrt
nums = {int(sqrt(x)) for x in range(30)}
print nums # Prints "set([0, 1, 2, 3, 4, 5])"

Tuples

一個tuple是一個(不可改變)有序值列表。Tuple在很多方面和list相似;最大的不同是tuples可以被用作字典的keys和sets的元素,但是lists卻不能。這裏是一個簡單的例子:

d = {(x, x + 1): x for x in range(10)}  # Create a dictionary with tuple keys
t = (5, 6)       # Create a tuple
print type(t)    # Prints "<type 'tuple'>"
print d[t]       # Prints "5"
print d[(1, 2)]  # Prints "1"

官方文檔中有更多的關於tuple的例子。

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)
# Prints "negative", "zero", "positive"

我們經常會將函數定義爲可選參數的,像這樣:

def hello(name, loud=False):
    if loud:
        print 'HELLO, %s!' % name.upper()
    else:
        print 'Hello, %s' % name
 
hello('Bob') # Prints "Hello, Bob"
hello('Fred', loud=True)  # Prints "HELLO, FRED!"

更多的關於Python函數的內容請參考官方文檔。

Classes

Python中定義類的語法是簡潔明瞭的:

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; prints "Hello, Fred"
g.greet(loud=True)   # Call an instance method; prints "HELLO, FRED!"

同樣可以在官方文檔中找到更多的內容。

======================================

關於Numpy和其他庫的使用將會在下一篇中介紹。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章