python技巧31[pythonTips1]
1 使用%來格式字符串
2 使用zip來將兩個list構造為一個dict
ages = [23, 40]
m = dict(zip(names,ages))
print (m)
3 不使用臨時變量來交換兩個值
4 使用str.join來連接字符串
result = ''.join(fruits)
5 使用in dict.keys()來判斷dict中是否包含指定的key
if 1 in d.keys():
print("d dict has the key 1")
6 使用set來去除list中的重復元素
l2 = set(l)
print(l2)
7 對于in操作,set要快于list,因為set是使用hash來存儲和查找的
8 使用with來讀寫文件,保證file對象的釋放
for line in f:
print (line)
f.readline() #f is cleanup here, here will get ValueError exception
9 使用emumerate來遍歷list
for index, value in enumerate(l):
print ('%d, %d' % (index, value))
10 分割字符串且去掉空白
result = [name for name in names.split(',') if name.strip()]
11 python中的a?b:c
12 Zen of python
The Zen of Python, by Tim Peters
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!
>>>
13 匿名函數lambda
print(add(1,2))
14 filter(bool_func,seq),在python3以后,filter為類,filter的功能相當于過濾器。調用一個布爾函數bool_func來迭代遍歷每個seq中的元素;返回一個使bool_seq返回值為true的元素的序列。
等價于(item for item in iterable if function(item)) 如果function不是None;等價于(item for item in iterable if item) 如果函數是None。
b=filter(None, a)
print (list(b))
c=filter(lambda x : x %2 == 0, a)
print(list(c))
d=filter(lambda x:x>5, a)
print (list(d))
#[1, 2, 3, 4, 5, 6, 7]
#[0, 2, 4, 6]
#[6, 7]
15 map(func,seq1[,seq2...]):在python3以后,map為類,map將函數func作用于給定序列的每個元素,并用一個列表來提供返回值;如果func為None,func表現為身份函數,返回一個含有每個序列中元素集合的n個元組的列表。
m = map(lambda x:x+3, a)
print(list(m))
#[3, 4, 5, 6, 7, 8, 9, 10]
16 reduce(func,seq[,init]):在python3以后,reduce一到functools模塊下,func為二元函數,將func作用于seq序列的元素,每次攜帶一對(先前的結果以及下一個序列的元素),連續的將現有的結果和下一個值作用在獲得的隨后的結果上,最后減少我們的序列為一個單一的返回值:如果初始值init給定,第一個比較會是init和第一個序列元素而不是序列的頭兩個元素。
a = [1,2,3,4,5]
s = functools.reduce(lambda x,y:x+y,a)
print(s)
#15
17 range用來返回一個list
for index in range(len(strings)):
print (index)
# prints '0 1 2 3 4'
18 all用來檢查list中所有的元素都滿足一定的條件
if all(number < 10 for number in numbers):
print ("Success!")
# Output: 'Success!'
19 any用來檢查list中是否至少由一個元素滿足一定的條件
if any(number < 0 for number in numbers):
print ('Success!')
else:
print('Fail!')
# Output: 'Fail!'
20 使用set來檢查list是否有重復的元素
if len(numbers) == len(set(numbers)):
print ('List is unique!')
# In this case, doesn't print anything
21 從已有的dict構造新的dict
email_at_dotcom = dict( [name, '.com' in email] for name, email in emails.items() )
print(email_at_dotcom)
# email_at_dotcom now is {'Dick': True, 'Jane': True, 'Stou': False}
22 And+or的執行過程
對于and語句,如果and左邊的是true,and右邊的值將被返回作為and的結果。
對于or語句,如果or左邊的是false,or將右邊的值將被返回作為or的結果。
# test = False
result = test and 'Test is True' or 'Test is False'
print(result)
# result is now 'Test is True'
23 檢查字符串是否包含子字符串
# string = 'Good bye' # False example
if string.find('Hi') != -1:
print ("Success!")
string = 'Hi there' # True example
# string = 'Good bye' # False example
if 'Hi' in string:
print ('Success!')
24 從list構造新的list
squares_under_10 = (number*number for number in numbers if number*number < 10)
# squares_under_10 is now a generator object, from which each successive value can be gotten by calling .next()
for square in squares_under_10:
print ( square)
# prints '1 4 9'
參考:
http://www.siafoo.net/article/52#id26
http://jeffxie.blog.chinabyte.com/2010/06/08/10/
http://jianpx.javaeye.com/blog/736669
完!


浙公網安備 33010602011771號