python你会吗_Python这些问题你会吗?
Python這些問題你會嗎?
final作用域的代碼一定會被執行嗎?
正常的情況下,finally作用域的代碼一定會被執行的,不管是否發生異常。哪怕是調用了sys.exit函數,finally也是會被執行的,那怎么樣才能讓finally代碼不執行了。
import time
choice = True
try:
if choice:
while True:
pass
else:
print "Please pull the plug on your computer sometime soon..."
time.sleep(60 * 60 * 24 * 365)
finally:
print "Finally ..."
上面的代碼主要是通過讓流程停滯在try作用域里,從而實現了需求。上面的代碼不排除有點投機取巧的意思,但是我們實習了題目的需求不是嗎。
可以對含有任意的元素的list進行排序嗎?
正常情況下:
>>> a = [1, '2', '3', '1']
>>> a.sort()
>>> a
[1, '1', '2', '3']
那是不是以為著,任何list都可以調用sort函數進行排序了?
>>> x = [1, 1j]
>>> x.sort()
Traceback (most recent call last):
File "", line 1, in ?
x.sort()
TypeError: cannot compare complex numbers using , >=
python里1j是一個特殊符號代表-1的平方根,出現這個問題的原因是sort函數調用的對象的 lt 函數來比較兩個對象的,而復雜的數字類型是不可比較的,也就說沒有實現 lt 函數,所以比較不了。因此,對于list里包含的對象如果都是可以比較的,也就是說實現了 lt 函數,那么對list調用sort函數是沒問題的。
Python可是使用++x或者x++之類的操作嗎?
++x操作是可以的,但是這個操作產生的結果和C語言里該操作產生的結果是不一樣的,Python里++x操作里的加好只是一個一元操作符,所以,++x等價于+(+x),所以++x == x。
x++操作是不合法的,雖然有些情況下,x++看著是合法的,比如:x++-y,但其實這個表達式等價于x+(+(-y)) = x-y,所以正常情況下,x++是不合法的。
Python里如何實現類似于C++里的cout<
實現的方法如下:
import sys
class ostream:
def __init__(self, file):
self.file = file
def __lshift__(self, obj):
self.file.write(str(obj));
return self
cout = ostream(sys.stdout)
cerr = ostream(sys.stderr)
nl = '\n'
cout << x << " " << y << nl
這地方并不是展示了一個新的python語法,這只是對python的str對象進行了封裝。
Python里如何實現C++里的printf函數?
在python2中,print是一個表達式,python3里是個函數。所以在python2里,我們可以這么做:
def printf(format, *args): print format % args,
上面的代碼雖然只有一行,但是,有些地方還是需要注意的。第一個地方,就是最后使用了都好結尾,這樣的話會更像c++的printf函數,如果想換行,則需要傳入換行符。第二個地方是這個代碼會在最后多打印一個空格,如果不想要這個空格,可以使用sys.stdout.write函數。第三的方面,這行代碼除了更像C++風格的printf,還有其他好處嗎?當然是有的,參數是比較靈活的。
Python里逗號等號(,=)是什么意思?
你可以能見過下面的代碼:
>>> x ,= range(1)
>>> x
0
實際上,沒有逗號等號(,=)這種操作符,上面的代碼等價于 (x,) = range(1)。 這只是一個賦值語句,在左邊有一個元組,意味著將元組的每個元素賦給右邊的相應元素; 在這種情況下,x被賦值為0
下面的代碼是否意味著python里有階乘的操作符?
比如下面的代碼:
assert 0!=1
assert 3!=6
assert 4!=24
assert 5!=120
其實上面的代碼并不是階乘的結果,只是有意的構造代碼的結果,實際上,上面的代碼等價于:
assert 0 != 1
assert 3 != 6
assert 4 != 24
assert 5 != 120
這樣一看,其實assert判斷是不等于的關系,所以都是True。
如何快速的給Python的對象增加屬性
通常我們的做法是,在對象定義的時候,定義相關的屬性,那如何自由的添加對象屬性了。
class Struct:
"A structure that can have any fields defined."
def __init__(self, **entries): self.__dict__.update(entries)
>>> options = Struct(answer=42, linelen=80, font='courier')
>>> options.answer
42
>>> options.answer = 'plastics'
>>> vars(options)
{'answer': 'plastics', 'font': 'courier', 'linelen': 80}
如何定義一個包含默認值的dict
在python2.7之前,必須定義一個類來處理這樣的需求,現在,可以使用collections.defaultdict和collections.Counte來實現。
from collections import Counter
words = 'this is a test this is only a test'.split()
>>> Counter(words)
Counter({'this': 2, 'test': 2, 'a': 2, 'is': 2, 'only': 1})
如何計算函數的執行時間
def timer(fn, *args):
"Time the application of fn to args. Return (result, seconds)."
import time
start = time.clock()
return fn(*args), time.clock() - start
>>> timer(max, range(1e6))
(999999, 0.4921875)
當然,python還有很多現成的輪子,可以更好的計算程序每個步驟的詳細信息。
如何實現單例模式
網上有很多方法,但是我知道的最簡單的方式如下:
def singleton(object):
"Raise an exception if an object of this class has been instantiated before."
cls = object.__class__
if hasattr(cls, '__instantiated'):
raise ValueError("%s is a Singleton class but is already instantiated" % cls)
cls.__instantiated = True
class YourClass:
"A singleton class to do something ..."
def __init__(self, args):
singleton(self)
...
轉載自我的博客: 捕蛇者說
總結
以上是生活随笔為你收集整理的python你会吗_Python这些问题你会吗?的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: pca各个向量之间的相关度_PCA主成分
 - 下一篇: python语言程序设计计算机二级难不难