python 學習 === ==一個程式新手打的文章,希望大家多指教:smile:== # data type ## interger interger只會被記憶體的大小限制,只要你記憶體夠大裝的下的,他就可以顯示給你,不像C的int被限制在$2^{32}$裡 ## 虛數 ```python= >>> x=(3+2j) * (4+9j) >>> x (-6+35j) >>> x.real -6.0 >>> x.imag 35.0 ``` ## 運算符 /:除法 //: 取商數 Example: ```python= >>>9//3 3 >>> -5//3 -2 ``` **:指數 ## List ```python= >>> number=['one', 'two', 'three', 'four'] >>> number[0] one ``` 那如果是number[-1]會是甚麼? ```python= >>> number[-1] four ``` 也可以使用":"在list中 ```python= >>> number[:3] ['one', 'two', 'three'] >>> number[1:-1] ['two,' 'three'] >>> number[-2:-1] ['three'] >>> number[-2:] ['three', 'four'] ``` list中:一律都是較小的數字在左邊,才會出現正常的狀況 若是左邊較大,就會出現[] ```python= >>> number[4:2] [] >>> number[-1:-3] [] ``` list可以去取代、加入或是移除 ```python= >>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> x[1] = "two" >>> x[8:9] = [] >>> x [1, 'two', 3, 4, 5, 6, 7, 8] ''' replace的也可以超過原本的size''' >>> x[5:7] = [6.0, 6.5, 7.0] >>> x [1, 'two', 3, 4, 5, 6.0, 6.5, 7.0, 8] >>> x[5:] [6.0, 6.5, 7.0, 8] ``` list中可以包含strings, tuples, lists, dictionaries, functions, file objects,tuple也可以 ### append 插到list的最後 ### pop 把最後一筆從list中移出 ### insert list.insert(第幾筆後,要insert的東西) ```python= >>> ttt=[1,2,3] >>> print(ttt.insert(1,5)) [1,5,2,3] ``` ### sort string的sort有兩種 一種是sorted,一種是list.sort(),區別在於list.sort()會存入原本的變數中,而sorted則不會 ```python= >>> a=[1,2,4,3,5] >>>print(sorted(a)) [1,2,3,4,5] >>> a [1,2,4,3,5] >>> a.sort() >>> a [1,2,3,4,5] ``` 可是sorted可以用在iterable上,諸如dictionary,string,tuple,set上面 另外sorted()有另一變數,reverse可以倒轉排序, ```python= >>> a=[1,2,4,3,5] >>> print(sorted(a,reverse=True)) [5,4,3,2,1] ``` 完整的sorted有這些,sorted(iterable[, cmp[, key[, reverse]]]), ~~cmp:比較的函數,~~ python3.6中已經不存在cmp了 key:作為比較的值 reverse:倒轉與否 ### index ```python= >>> x=[1,2,2] >>> x.index(1) 0 #可是如果有兩個,就只會出現第一個的index >>>x.index(2) 1 ``` ## Tuples 與list相似,但是創造後不能更動,並且只分成index跟count兩種;tuples最主要的目的是作為字典,當tuples不需要去更改的時候,tuple更有效率 ```python= (1,)'''一個element的tuple也需要","''' t=(1, 2, 3, 4, 5, 6, 7, 8, 12) '''tuple不支援t[0]=123之類的行為''' ``` ## string 此為python的**強項**, "A string in double quotes can contain 'single quote' characters." 'A string in single quotes can contain "double quote" characters.' '''\tA string which starts with a tab; ends with a newline character.\n''' """This is a triple double quoted string, the only kind that can contain real newlines.""" 也就是說,''的string中可以包含"",""也可以包含'',而且\t跟\n都可以在string中作用。 另外就in, $*$(不是str$*$str而是str $\ast$ 2會出現兩次這樣),+ ,也可以用len, max, min等等, 但是=在這邊是不能使用的,要利用replace來改變string中的value。 string中有像是matlab的用法,例如 ```python= >>> s="0123456" >>> print(s[0:2]) 01 #其中採取左開右閉的原則,也就是說會碰到s[0]卻不會碰到s[2] >>> print(s[0:7:2]) 0246 #輸出s[0]到s[6],並且以2為間隔 >>> print(s[:]) 0123456 >>> print(s[::-1]) 6543210 ``` ### join string中有個功能叫做join,可以把一個string作為string的list中間連結橋梁,有點饒口,有點難懂,看下面例子 ```python= >>> bridge="loves" >>> stringlist=["Antony","Melody"] >>> bridge.join(stringlist) AntonylovesMelody ``` ### string format 使用%d,%s等像是C語言的輸入法,之後使用%接上一個tuple ```python= firstname='tony' lastname='Ko' print('Hello %s %s, welcom to my HackMD~'%(firstname, lastname)) ``` 不過好像逐漸變化成下面這種,利用{}跟:來對%進行取代 ```python= >>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序 'hello world' >>> "{0} {1}".format("hello", "world") # 设置指定位置 'hello world' >>> "{1} {0} {1}".format("hello", "world") # 设置指定位置 'world hello world' ``` 也可以搭配dictionary 或是 list 來使用 ```python= print('{name}{adj}'.format(name='作者',adj='好帥')) #作者好帥 data={'name':'作者','形容詞':'好帥'}#利用dic print('{name}{形容詞}'.format(**data)) #作者好帥 #**代表把裡面的參數放到dic中供函數使用,若是*則代表放到tuple中供函數使用,再自訂義函數那邊也有相似的東西 importantdata=['python學習的作者','好帥']#利用list test=['好自戀'] print('{0[0]}{1[0]}'.format(importantdata,test)) #python學習的作者好自戀 ``` ### 怎麼改string中的字 因為直接s[0]='x'這種東西是不存在的 我們可以利用join,例如: ```python= >>> string = "abracadabra" >>> l = list(string) >>> l[5] = 'k' >>> string = ''.join(l) >>> print string abrackdabra ``` 或是用[:] ```python= >>> string = string[:5] + "k" + string[6:] >>> print string abrackdabra ``` ## Dictionaries 其中有key跟value,理所當然的ket只有一個,若是之後有相同的key,那就會直接把前面的取代掉,像這樣 ```python= >>> x = {1: "one", 2: "two", 1:"change"} >>> x {1:"change", 2:"two"} ``` 而且,key是不變的,所以key可以是string, 數字, touple, 但是就是不能是list。 所以dictionaries也是立於查詢,只是跟touple比起來,dictionaries的value可以改。 ## sets 可以跟list比較一下,先看例子 ```python= >>> x = set([1, 2, 3, 1, 3, 5]) >>> x {1, 2, 3, 5} ``` 重點在於裡面的成員是唯一的 ## file objects 寫法是把某檔案打開到某個變數裡 ```python= >>> f=open("myfile", "w")"""myfile應該跟py檔在同一個資料夾,不然要打絕對位置,後面的變數決定要做的事情""" >>> f.write("English")"""試過中文,似乎沒有辦法寫入""" ``` 目前只有試過open txt檔,其他的還要嘗試。 另外,mode一次只能開一個,不能wr都開 ## iter 迭代器 https://blog.csdn.net/liweibin1994/article/details/77374854 # 內置函數 ## [for](https://hackmd.io/V6GzhLMWTs-RfoPnqkZQDw) ## del 刪除的是變數,而不是數據 ```python= a=1 b=a del a print(b)#1 ``` 在list上面的使用 ```python= x=[1,2,3] first=x[0] del x[0] print(x,first)#[2, 3] 1 ``` ## Execptions 為try-except-else-finally 也可用在我自己定義的exception之中。 用with可以更精簡的去封裝try-except-finally example: ```python= filename = "myfile.txt" try: f = open(filename, "r") for line in f: print(f) except Exception as e: raise e finally: f.close() ``` 這樣如果最後沒有寫f.close()那就會一直開著忘記關閉, 可以精簡成 ```python= filename = "myfile.txt" with open(filename, "r") as f: for line in f: print(f) ``` 可以自動處理exception,也會在最後自己將文件關閉。 # 自定義函數 ## 超過原定義輸入變數 ```python= >>> def fun(x,y,*tup): ...: print ((x,y)+tup) >>> fun(1,2,1,2) (1,2,1,2) ``` $*$tup表示,超過的變數收集成一個tuple來進行運算 另外也有$**$,這樣會收集成diction ```python= >>> def funct4(x, y=1, z=1, **kwargs): ... print(x, y, z, kwargs) >>> funct4(1, 2, m=5, n=9, z=3) 1 2 3 {'n': 9, 'm': 5} ``` # Module 我們在程式最開始的部分都會import一些東西,那些被叫做module。 可以利用內建的函式庫來創造。 # Class ## [python子類調用父類](https://www.itread01.com/content/1512454937.html) # Error ## SyntaxError:invalid syntax "語法錯誤,不正確的語法",python中比較常出現的是python2與pyhton3的差別,所以可能直接copy別人的code也會有這個錯。 ## IndentationError:expected an indented block python 對於tab與空白極為敏感,所以要注意這些部分,記得冒號下一句往往就是要tab或是空格,**但是空格與tab不可混用** ## SyntaxError: non-default argument follows default argument def定義函數的時候,有預設的值要放後面,沒有預設的值要放前面, ```python= def test(x='None',a): print(x,a) #那我寫這樣 test(1) #他應該顯示甚麼? ``` 所以沒有預設值的才要放在前面。 # 常用library ## [numpy](/uOxrtALGTB2QPvuVRAqFRQ) 先學numpy在學pandas ## panda 之後打 ## .json 如果拿到一檔案,裡面的內容像是list或是dict可以處理,那就使用json黨下去處理,load進來之後便可以直接變成list或是dict 若是想要做json檔,就用dumps # 雜項 ## 清空變數 輸入 reset 會清除所有變數。 del a 會清除a這個變數。 ## 型態轉換 若是要把a(type為int)轉換為float,只需要float(a)就可以了 [01-2 Python內建型態轉換(int, float, str)](https://github.com/tomlinNTUB/Python/blob/master/01-2%20%E5%85%A7%E5%BB%BA%E5%9E%8B%E6%85%8B%E8%BD%89%E6%8F%9B(int%2C%20float%2C%20str).md) # 細項觀念 ## python中的變數要想像為label而非container 這個觀念可以從下面這個例子看出 ```python= >>> a=[1,2,3] >>> b=a >>> c=b >>> b[1]=9 >>> print(a,b,c) [1, 9, 3] [1, 9, 3] [1, 9, 3] ``` 若是每個varible都是個獨立container那改變b[1]便不會出現最終的答案,但是如果這個例子是用constant或是immutable value就會看不出來 ```python= >>> a=1 >>> b=a >>> c=b >>> b=5 >>> print(a,b,c) 1,5,1 ``` 不會變的主因是,1這個integer是不會變的,而a refer到1,所以b=5這行才會只有讓b改變 而mutable的觀念可以往下看,幫助了解 ## [mutable與immutable](https://hackmd.io/iWLgxGsbRo2UOCGMziFkkw) ## [python 判断对象是否为None](https://blog.csdn.net/primeprime/article/details/77186109) # 進階點 ## [Regular Expression(正規表達式)](https://hackmd.io/DF64Tob6RQalKGa_nGnoGQ?both) # 繼續精進 ## [爬蟲相關] ### [Flask 學習](/dZ3PA3GmRh2N-uULG-H6nw) # 引用或資料來源 [菜鳥教程](http://www.runoob.com/) [Built-in Functions — Python 3.7.3 documentation](https://docs.python.org/3/library/functions.html) [IndentationError:expected an indented block错误的解决办法](https://blog.csdn.net/hongkangwl/article/details/16344749) [The Quick Python Book, Second Edition](http://www.astro.caltech.edu/~vieira/The_Quick_Python_Book.pdf) [林宏仁的 Python 筆記](https://github.com/tomlinNTUB/Python) [[Python]如何在Python排序(Python Sorting)](http://swaywang.blogspot.com/2012/05/pythonpythonpython-sorting.html) [理解 Python object 的 mutable 和 immutable](http://wsfdl.com/python/2013/08/14/%E7%90%86%E8%A7%A3Python%E7%9A%84mutable%E5%92%8Cimmutable.html) ###### tags: `python`