標籤:

深度學習中的Python語言1:Python基礎數據類型、容器、函數和類的介紹

目錄:

  1. 基本數據類型
  2. 容器(Containers)介紹
    1. 列表(List)
    2. 詞典(Dictionaries)
    3. 集合(Sets)
    4. 元組(Tuples)
  3. 函數(Functions)
  4. 類(Classes)

開始正文之前,請先安裝Python(這裡不再贅述如何安裝,網上有很多教程)。

但是需要說明的是Python的版本,由於版本不同,尤其是Python 2.7和Python 3.0之後的版本有較大區別,所以有必要聲明一下,本文用的Python版本是3.6.1。

如何查看Python版本,在命令行輸入:

python --versionn

下面開始正文:

1. 基本數據類型

數字(Numbers)

主要有整數型和浮點型,基本上操作和其他語言類似:

x = 3nprint(type(x)) # Prints "<class int>"nprint(x) # Prints "3"nprint(x + 1) # Addition; prints "4"nprint(x - 1) # Subtraction; prints "2"nprint(x * 2) # Multiplication; prints "6"nprint(x ** 2) # Exponentiation; prints "9"nx += 1nprint(x) # Prints "4"nx *= 2nprint(x) # Prints "8"ny = 2.5nprint(type(y)) # Prints "<class float>"nprint(y, y + 1, y * 2, y ** 2) # Prints "2.5 3.5 5.0 6.25"n

上面的代碼我們可以學到查看類型的type()的用法。

值得注意的是,Python不使用x++或x--這類增量運算符。

另外Python內置了一些複雜數字的類型,可以點擊這裡。

布爾型(Booleans)

這個也是程序語言最常見最基本的類型之一了。

t = Truenf = Falsenprint(type(t)) # Prints "<class bool>"nprint(t and f) # Logical AND; prints "False"nprint(t or f) # Logical OR; prints "True"nprint(not t) # Logical NOT; prints "False"nprint(t != f) # Logical XOR; prints "True"n

這裡值得注意的是,Python使用單詞(如 and,or等)而不是符號(如&&和||等)來表達邏輯關係。

字元串(string)

常見類型:字元串

hello = hello # String literals can use single quotesnworld = "world" # or double quotes; it does not matter.nprint(hello) # Prints "hello"nprint(len(hello)) # String length; prints "5"nhw = hello + + world # String concatenationnprint(hw) # prints "hello world"nhw12 = %s %s %d % (hello, world, 12) # sprintf style string formattingnprint(hw12) # prints "hello world 12"n

字元串的基礎操作,可以用+連接字元串,非常方便。

s = "hello"nprint(s.capitalize()) # Capitalize a string; prints "Hello"nprint(s.upper()) # Convert a string to uppercase; prints "HELLO"nprint(s.rjust(7)) # Right-justify a string, padding with spaces; prints " hello"nprint(s.center(7)) # Center a string, padding with spaces; prints " hello "nprint(s.replace(l, (ell))) # Replace all instances of one substring with another;n # prints "he(ell)(ell)o"nprint( world .strip()) # Strip leading and trailing whitespace; prints "world"n

Python對字元串提供了非常多的支持,這裡挖一個坑,以後慢慢補充。

另外,官方文檔。

2. 容器(Containers)介紹

Python內置了許多容器類型:

列表(List)

列表就是python版的array(c語言中的),但是可以調整大小,並且可以包含不同類型的數據。

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

append是一個很常用的功能。

當列表中的元素是數值類型時,可以用列表表示數學中的向量!!!這在機器學習中非常常用!!!重要的事情要加粗!!!

關於list的官方文檔在這裡。

切片(slicing)是選取列表中元素的重要方式。這是一種很方便的選取列表元素的方式。如下所示:

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

循環(loops)也是一種非常常用的方式。

animals = [cat, dog, monkey] nfor animal in animals: n print(animal) n# Prints "cat", "dog", "monkey", each on its own line. n

這裡可以用in循環提取list中的元素,不僅非常方便,而且這種模仿英語文法的設計使代碼的可讀性非常高。

enumerate函數:如果你還想要選擇每個元素的索引(index),可以使用enumerate函數。

animals = [cat, dog, monkey]nfor idx, animal in enumerate(animals):n print(#%d: %s % (idx + 1, animal))n# Prints "#1: cat", "#2: dog", "#3: monkey", each on its own linen

列表推導式,能夠方便 解決下類問題:

nums = [0, 1, 2, 3, 4] nsquares = [] nfor x in nums: n squares.append(x ** 2) nprint(squares) # Prints [0, 1, 4, 9, 16] n

你可以使用列表推導式輕鬆解決:

nums = [0, 1, 2, 3, 4]nsquares = [x ** 2 for x in nums]nprint(squares) # Prints [0, 1, 4, 9, 16]n

很酷的方式!

列表推導式還可以包含條件:

nums = [0, 1, 2, 3, 4]neven_squares = [x ** 2 for x in nums if x % 2 == 0]nprint(even_squares) # Prints "[0, 4, 16]"n

是不是讀起來特別通順的感覺,這就是python語言簡潔、高效、可讀性高的體現!!

詞典(Dictionaries)

詞典用來成對的存儲(關鍵字,值),如下所示:

d = {cat: cute, dog: furry} # Create a new dictionary with some datanprint(d[cat]) # Get an entry from a dictionary; prints "cute"nprint(cat in d) # Check if a dictionary has a given key; prints "True"nd[fish] = wet # Set an entry in a dictionarynprint(d[fish]) # Prints "wet"n# print(d[monkey]) # KeyError: monkey not a key of dnprint(d.get(monkey, N/A)) # Get an element with a default; prints "N/A"nprint(d.get(fish, N/A)) # Get an element with a default; prints "wet"ndel d[fish] # Remove an element from a dictionarynprint(d.get(fish, N/A)) # "fish" is no longer a key; prints "N/A"n

注意創建詞典用的是大括弧{ },而創建列表用的是方括弧[ ],注意兩者區別。

獲取元素值的話詞典和列表都是用中括弧[ ],而詞典還有一個比較方便的用法是用get屬性。

更多詳細內容,看官方文檔。

同樣,這裡我們討論一下詞典的循環操作:

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

這裡和列表對比看,for後面的變數代表的是詞典里的關鍵字(key),d[animal]得到的就是每個關鍵字對應的值(value)。而列表裡面,for後面的變數代表的是列表裡面的元素(因為列表裡沒有關鍵字)。

python的優雅體現在,還有更簡單直觀的方式:

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

只需要使用.items()方法就直接獲得關鍵字和值了。

詞典推導式,前面講了列表推導式,詞典也可以採用這種方便的操作:

nums = [0, 1, 2, 3, 4]neven_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}nprint(even_num_to_square) # Prints "{0: 0, 2: 4, 4: 16}"n

集合(Sets)

集合是一系列無序元素的組合:

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

我們還是對比來看,創建集合採用的是大括弧{},這與詞典相同,與列表不同(列表是[ ]);集合內的元素用逗號分開,與詞典不同在於,元素不是成對出現的。

另外還有一點,由於是無序組合,因此不能用數字索引元素,這點是與列表的區別。

你可以採用和循環索引列表的方式索引集合,但是注意,這裡唯一的不同是,由於集合是無序的,因此,循環時相當於每一次隨機提取一個元素:

animals = {cat, dog, fish}nfor idx, animal in enumerate(animals):n print(#%d: %s % (idx + 1, animal))n

同樣,集合推導式來了:

from math import sqrtnnums = {int(sqrt(x)) for x in range(30)}nprint(nums) # Prints "{0, 1, 2, 3, 4, 5}"n

元組(Tuples)

元組和列表非常類似,但是一個很大的不同是,元組可以作為詞典的關鍵字,也可以作為集合的元素,但是列表不能!

下面是一個例子:

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

更多關於元祖的信息,請看官網。

3. 函數(Functions)

Python中用關鍵字『def』來定義函數,見例子如下:

def sign(x):n if x > 0:n return positiven elif x < 0:n return negativen else:n return zeronnfor x in [-1, 0, 1]:n print(sign(x))n# Prints "negative", "zero", "positive"n

我們經常給函數定義可選擇的參數:

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

更多見官方文檔。

4. 類(Classes)

定義類的話,用關鍵字class:

class Greeter(object):nn # Constructorn def __init__(self, name):n self.name = name # Create an instance variablenn # Instance methodn def greet(self, loud=False):n if loud:n print(HELLO, %s! % self.name.upper())n else:n print(Hello, %s % self.name)nng = Greeter(Fred) # Construct an instance of the Greeter classng.greet() # Call an instance method; prints "Hello, Fred"ng.greet(loud=True) # Call an instance method; prints "HELLO, FRED!"n

官方文檔。


推薦閱讀:

【精心解讀】關於Jupyter Notebook的28個技巧
為什麼要學習Python?
scala和groovy的優勢有哪些?

TAG:Python |