建議1:理解pythonic概念
《The Zen of the Python》(python之禪)相信大家都聽說過。
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
斷斷續續用了python一年多時間,沒學得多深入,但是看多了說python哲學的帖子和文章,我覺得對pythonic的理解,得多看別人寫的程式碼,有些實現讓人覺得很優美,或許這就是pythonic。
(1)虛擬碼可以直接改成python程式碼
根據維基百科中快速排序的描述
可以直接翻譯成python程式碼:
def quick_sort(array):
if len(array) <= 1:
return array
less = []
greater = []
pivot = array.pop()
for x in array:
if x < pivot:
less.append(x)
else:
greater.append(x)
return quick_sort(less) + [pivot] + quick_sort(greater)
array = [random.randint(-10000000, 1000000) for x in range(1000)]
A = sorted(array)
B = quick_sort(array)
for i in range(len(array)):
if A[i] != B[i]:
print('not equel!' )
print('index are: {index}'.format(index=i))
print(A[i], B[i])
break
else:
print('yes')
實現快排只要短短几行,而且容易理解
(2)交換a, b兩個變數的值
在c/c++/java裡:
int a=1, b=2;
int c = a;
a = b;
b = c;
c++ STL:
std::swap(a, b)
位運算:
a = a^b;
b = a^b;
a = a^b;
在python裡:
a, b = b, a
(3)使用上下文管理器
with open(filename, mode='r', encoding='utf-8') as fp:
line = fp.readline()
do something
使用上下文管理器後,不需要顯示的關閉,將由系統自動關閉檔案
(4)字串格式化:
以往我是這樣輸出的print('%s' % 'lrh')
這樣十分不直觀
推薦使用str.format():
print('{name} from {country}'.format(name='lrh', country='china'))