Python Fundamentals

Functions

add_numbers updated to take an optional 3rd parameter. Using print allows printing of multiple expressions within a single cell.

def add_numbers(x,y,z=None):
        if (z==None):
        return x+y
    else:
        return x+y+z

print(add_numbers(1, 2))
print(add_numbers(1, 2, 3))

output:

3
6

add_numbers updated to take an optional flag parameter.

def add_numbers(x, y, z=None, flag=False):
    if (flag):
        print('Flag is true!')
    if (z==None):
        return x + y
    else:
        return x + y + z
    
print(add_numbers(1, 2, flag=True))

output:

Flag is true!
3

Reading and Writing CSV files

To show CVS files in console, use command !cat xxx.csv.
use “with” to open files

import csv

%precision 2

with open('mpg.csv') as csvfile:
    mpg = list(csv.DictReader(csvfile))
    
mpg[:3] # The first three dictionaries in our list.

用了 with,就不需要 file.close(),會自動關(guān)閉以及處理異常,相當(dāng)于 finally 的功能。

The Python Programming Language: Dates and Times

import datetime as dt
import time as tm
 
tm.time()
 
dtnow = dt.datetime.fromtimestamp(tm.time())
dtnow 
 
dtnow.year, dtnow.month, dtnow.day, dtnow.hour, dtnow.minute, dtnow.second # get year, month, day, etc.from a datetime
 
delta = dt.timedelta(days = 100) # create a timedelta of 100 days
delta
 
today = dt.date.today()
today - delta # the date 100 days ago
today > today-delta # compare dates

Map()

Here's an example of mapping the min function between two lists.

store1 = [10.00, 11.00, 12.34, 2.34]
store2 = [9.00, 11.10, 12.34, 2.01]
cheapest = map(min, store1, store2)
cheapest

the cheapest 不會輸出具體的值,只會輸出一個地址,除非你進(jìn)去:

for item in cheapest:
    print(item)

output:

9.0
11.0
12.34
2.01

Lambda and List Comprehensions

Here's an example of lambda that takes in three parameters and adds the first two.

my_function = lambda a, b, c : a + b
my_function(a, b, c)

And list comprehension.

如果沒有 else, 就是 a for i in items if C;如果加上 else,就需要調(diào)換順序: a if C else b for i in items

The Python Programming Language: Numerical Python

  1. 檢查矩陣是幾乘以幾,使用 m.shape。
  2. 可以用 arrange 函數(shù)直接生成 array,比如 n = np.arange(0, 30, 2) # start at 0 count up by 2, stop before 30。
  3. 接著 reshape 可以把 array 里的一行的數(shù)重新分布,例如 n = n.reshape(3, 5) # reshape array to be 3x5。reshape 函數(shù)改變調(diào)用數(shù)組的形狀并返回該數(shù)組,而 resize 函數(shù)改變調(diào)用數(shù)組自身。反操作 ravel 直接把 array 攤平。
  4. 2中,如果不知道步長,只知道元素的個數(shù),可以用 linspace 函數(shù),例如 o = np.linspace(0, 4, 9) # return 9 evenly spaced values from 0 to 4。
  5. 在創(chuàng)建 array 時可以直接用 dtype 指定數(shù)據(jù)的類型,例如復(fù)數(shù) c = np.array( [ [1, 2], [3, 4] ] ), complex),就會輸出array( [ [1.+0.j, 2.+0.j], [3.+0.j, 4.+0.j ] ] )
  6. 用函數(shù) zeros 可創(chuàng)建一個全是 0 的 array,用函數(shù) ones 可創(chuàng)建一個全為1的 array,函數(shù) empty 創(chuàng)建一個內(nèi)容隨機(jī)并且依賴與內(nèi)存狀態(tài)的 array,函數(shù) eye 可創(chuàng)建一個單位矩陣,函數(shù) diag(A) 可利用已有的 array 創(chuàng)建對角矩陣。默認(rèn)創(chuàng)建的 array 類型(dtype) 都是 float64。
  7. 普通運算操作符對 array 里的元素是逐個處理的,包括乘法和乘方,矩陣乘法要用函數(shù) .dot(A, B)
  8. 組合兩個 array,水平組合函數(shù) hstack( [A, B]),等同于 concatenate( [A, B], axis=1);垂直組合函數(shù) vstack( [A, B] ),等同于 concatenate( [A, B], axis=0);深度組合函數(shù) dstack( [A, B] ),在第三個軸上進(jìn)行組合。同理反操作,也有分割函數(shù) hsplit、vsplitdsplitsplit,最后一個也是要有 axis=1 或者 axis = 0。
  9. 重復(fù)的區(qū)別:np.array([1, 2, 3] * 3) 返回 array([1, 2, 3, 1, 2, 3, 1, 2, 3]);而 np.repeat([1, 2, 3], 3) 返回 array([1, 1, 1, 2, 2, 2, 3, 3, 3])
  10. a.argmax()a.argmin() 返回 array 中最大和最小值的 index。
  11. 產(chǎn)生隨機(jī) array 代碼例子:test = np.random.randint(0, 10, (4,3))
  12. 遍歷方法。通過 row:for row in test:;通過 index:for i in range(len(test)):;通過 row 和 index:for i, row in enumerate(test):;通過 zip 函數(shù)遍歷多個:for i, j in zip(test, test2):。
  13. 如下代碼塊反映了不復(fù)制、淺復(fù)制 (view) 和復(fù)制 (copy):
  • 不復(fù)制:

      >>> a = arange(12)
      >>> b = a      #不創(chuàng)建新對象
      >>> b is a     # a和b是同一個數(shù)組對象的兩個名字
      True  
      >>> b.shape = 3,4    #也改變了a的形狀  
      >>> a.shape  
      (3, 4)  
    
  • 淺復(fù)制 (view):

      >>> c = a.view()  
      >>> c is a  
      False  
      >>> c.base is a      #c是a持有數(shù)據(jù)的鏡像  
      True  
      >>> c.flags.owndata  
      False  
      >>>  
      >>> c.shape = 2,6    # a的形狀沒變  
      >>> a.shape  
      (3, 4)  
      >>> c[0,4] = 1234        #a的數(shù)據(jù)改變了  
      >>> a  
      array([[   0,    1,    2,    3],  
             [1234,    5,    6,    7],  
             [   8,    9,   10,   11]])  
    

切片數(shù)組返回它的一個 view

    >>> s = a[ : , 1:3]     # 獲得每一行1,2處的元素  
    >>> s[:] = 10           # s[:] 是s的鏡像。注意區(qū)別s=10 and s[:]=10  
    >>> a  
    array([[   0,   10,   10,    3],  
           [1234,   10,   10,    7],  
           [   8,   10,   10,   11]])  
  • 深復(fù)制 (copy)

      >>> d = a.copy()       #創(chuàng)建了一個含有新數(shù)據(jù)的新數(shù)組對象  
      >>> d is a  
      False  
      >>> d.base is a        #d和a現(xiàn)在沒有任何關(guān)系  
      False  
      >>> d[0,0] = 9999  
      >>> a  
      array([[   0,   10,   10,    3],  
             [1234,   10,   10,    7],  
             [   8,   10,   10,   11]]) 
    
  1. We can perform conditional indexing. Here we are selecting values from the array that are greater than 30. (Also see np.where)

    >>> r = np.array ([[ 0,  1,  2,  3,  4,  5],
           [ 6,  7,  8,  9, 10, 11],
           [12, 13, 14, 15, 16, 17],
           [18, 19, 20, 21, 22, 23],
           [24, 25, 26, 27, 28, 29],
           [30, 31, 32, 33, 34, 35]])
    >>> r[r > 30]
    array([31, 32, 33, 34, 35])
    >>> r[r > 30] = 30
    array([[ 0,  1,  2,  3,  4,  5],
           [ 6,  7,  8,  9, 10, 11],
           [12, 13, 14, 15, 16, 17],
           [18, 19, 20, 21, 22, 23],
           [24, 25, 26, 27, 28, 29],
           [30, 30, 30, 30, 30, 30]])
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容