python3.0 notes

目標:使用python寫出正確語法格式的程序,並讓它能高效的跑起來。python的確是一個很好的編寫腳本的語言,本身自帶了很多好的結構。
1.8//5 output 1 8/5 output 1.6 新增加了//運算符,老實說不怎麼喜歡這個改變,個人更傾向於int(8/5)來獲得8//5的計算
2.In interactive mode,可以通過_得到上次的屏幕輸出
3.print 變成一個函數 print()
4.一些list操作:
>>> # Replace some items:
... a[0:2] = [1, 12]
>>> a
[1, 12, 123, 1234]
>>> # Remove some:
... a[0:2] = []
>>> a
[123, 1234]
>>> # Insert some:
... a[1:1] = [’bletch’, ’xyzzy’]
>>> a
[123, ’bletch’, ’xyzzy’, 1234]
>>> # Insert (a copy of) itself at the beginning
>>> a[:0] = a
>>> a
[123, ’bletch’, ’xyzzy’, 1234, 123, ’bletch’, ’xyzzy’, 1234]
>>> # Clear the list: replace all items with an empty list
>>> a[:] = []
>>> a
[]
5.The keyword end can be used to avoid the newline after the output, or end the output with a different string:
print(b, end=’ ’)
6.range()返回的是一個可以iterable的對象,這個對象並沒有展開爲一個list,這樣可以節省空間。這些對象可以通過一個迭代器iterator來進行遍歷,比如for語句,list()則是另一個iterator
7.Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list(with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement。有些時候這個else語句的確還是蠻有用的,省去了其他語言需要設置一個flag的代價。
8.*操作符用來unpack list 或者tuple:
>>> args = [3, 6]
>>> list(range(*args)) # call with arguments unpacked from a list
[3, 4, 5]
9.**操作符用來unpack dictionary:
>>> def parrot(voltage, state=’a stiff’, action=’voom’):
... print("-- This parrot wouldn’t", action, end=’ ’)
... print("if you put", voltage, "volts through it.", end=’ ’)
... print("E’s", state, "!")
...
>>> d = {"voltage": "four million", "state": "bleedin’ demised", "action": "VOOM"}
>>> parrot(**d)
10.list comprehension:
>>> [3*x for x in vec if x > 3]
11.創建一個空的set,需要使用set()
12.dict()可以從list直接創建一個dictionary,但是要求list的每一項都是一個key:value的tuple:
>>> dict([(’sape’, 4139), (’guido’, 4127), (’jack’, 4098)])
{’sape’: 4139, ’jack’: 4098, ’guido’: 4127}
13.dict comprehensions:{x: x**2 for x in (2, 4, 6)}
14.another dict參數:dict(sape=4139, guido=4127, jack=4098)
15.loop through a sequence,使用enumerate()可以同時取得position index和value:
>>> for i, v in enumerate([’tic’, ’tac’, ’toe’]):
16.zip()函數:
>>> questions = [’name’, ’quest’, ’favorite color’]
>>> answers = [’lancelot’, ’the holy grail’, ’blue’]
>>> for q, a in zip(questions, answers):
... print(’What is your {0}? It is {1}.’.format(q, a))
17.import imp; imp.reload(modulename)可以重新加載模塊
18.from module important * 可以引入模塊中的所有方法和變量,除了以_開頭的
19.The module compileall can create .pyc files (or .pyo files when -O is used) for all modules in a directory.
20.the new built-in vars() function, which returns a dictionary containing all local variables
21.print()函數提供{key:option}格式化的方式,還有string的format()來取代以前的%操作,雖然%操作被保留但是最終還是會從語言中被刪除,所以以後還是不要再使用。
22.except Exception as e 以前是 except Exception,e,感覺現在的語法更容易接受。
23.The with statement allows objects like files to be used in a way that ensures they are always cleaned up promptly
and correctly.
with open("myfile.txt") as f:
for line in f:
print(line)
After the statement is executed, the file f is always closed, even if a problem was encountered while processing
the lines.
一個很奇怪的語法,沒弄懂什麼意思。
24.關於scope和namespace,寫了一長段的東西,看了半天,還不如看下面的一個例子:
def scope_test():
def do_local():
spam = "local spam"
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)
scope_test()
print("In global scope:", spam)

output is :
after local assignment: test spam
after nonlocal assignment:nonlocal spam
after global assignment:nonlocal spam
In global scope:global spam

這裏的函數裏面又定義函數第一次看到,fresh。


25.yield 語句可以幫助創建iterator,它會記錄上次訪問數據的位置,並會自動產生StopIteration:
def reverse(data):
for index in range(len(data)-1, -1, -1):
yield data[index]
>>> for char in reverse(’golf’):
... print(char)
...

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