python 基本語法速覽,快速入門
https://zhuanlan.zhihu.com/p/24536868
學習參考於這個博文。
我做一個筆記。
關於python一些常用的語法快速的預覽,適合已經掌握一門編程語言的人。零基礎,沒有任何編程經驗的不適用快速入門。
基礎數據類型
和其他主流語言一樣,Python為我們提供了包括integer、float、boolean、strings等在內的很多基礎類型。
數值類型
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內置的也提供了長整型與其他復雜數值類型的整合,可以參考這裏。
布爾類型
Python提供了常見的邏輯操作符,不過需要註意的是Python中並沒有使用&&、||等,而是直接使用了英文單詞。
t = 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"
字符串
Python對於字符串的支持還是很好的,不過需要註意到utf-8編碼問題。
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"
Python中的字符串對象還包含了很多有用的方法,譬如:
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"
可以在這裏中查看詳細的方法列表。
復雜數據類型
列表
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‘]"
同樣你可以在文檔中查看更多的細節。
切片
Python中對於數組的訪問也相當人性化,通過簡單的操作符即可以完成對於數組中子數組的截取。
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]"
遍歷
你可以使用基本的for循環來遍歷數組中的元素,就像下面介個樣紙:
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
變換
在編程中我們經常需要對數組進行變換,比較著名的我們可以使用map、reduce、filter這幾個函數,而在Python中提供了非常方便的List Comprehension操作符。譬如我們需要對數組中元素進行依次平方操作
nums = [0, 1, 2, 3, 4] squares = [] for x in nums: squares.append(x ** 2) print squares # Prints [0, 1, 4, 9, 16]
我們可以簡寫為如下方式:
nums = [0, 1, 2, 3, 4] squares = [x ** 2 for x in nums] 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]"
字典
Python中的字典類型即類似於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"
更多的語法細節可以參考這裏。
遍歷
對於字典的遍歷也非常簡單:
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"
如果你希望同時訪問鍵和其對應的值,可以使用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"
變換
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}"
Set
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"
更多語法細節可以參考這裏。
遍歷
集合遍歷的語法和數組遍歷很類似,不過因為集合本身是無序的,因此你不能夠依賴於遍歷的順序來預測集合中元素的順序:
animals = {‘cat‘, ‘dog‘, ‘fish‘} for idx, animal in enumerate(animals): print ‘#%d: %s‘ % (idx + 1, animal) # Prints "#1: fish", "#2: dog", "#3: cat"
變換
from math import sqrt nums = {int(sqrt(x)) for x in range(30)} print nums # Prints "set([0, 1, 2, 3, 4, 5])"
Tuples
Python中的Tuple指不可變的有序元素集合,Tuple很類似於列表,不過區別在於Tuple可以做字典中的鍵類型,而列表則不可以。
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"
Function:函數
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"
同時,Python中的函數還支持可選參數:
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!"
更多的語法細節可以參考這裏。
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!"
可以參考這裏獲取更多信息。
python 基本語法速覽,快速入門