python技巧31[pythonTips1]

 

1 使用%来格式字符串

print ( " hello %s : %s "   %  ( " AAA " " you are so nice " ))

 

2 使用zip来将两个list构造为一个dict

names  =  [ ' jianpx ' ' yue ' ]   
ages 
=  [ 23 40 ]   
=  dict(zip(names,ages)) 
print  (m)

 

3 不使用临时变量来交换两个值

a,b  =  b,a

 

4 使用str.join来连接字符串

fruits  =  [ ' apple ' ' banana ' ]   
result 
=   '' .join(fruits) 

 

5 使用in dict.keys()来判断dict中是否包含指定的key

=  { 1 : " v1 " 2 : " v2 " }
if   1   in  d.keys():
  
print ( " d dict has the key 1 " )

 

6 使用set来去除list中的重复元素

=  [ 1 , 2 , 2 , 3 ]
l2 
=  set(l)
print (l2)

 

7 对于in操作,set要快于list,因为set是使用hash来存储和查找的

 

8 使用with来读写文件,保证file对象的释放

  with open( " myfile.txt " ) as f:
     
for  line  in  f:
         
print  (line)
  f.readline() 
# f is cleanup here, here will get ValueError exception

 

9 使用emumerate来遍历list

=  [ 1 , 3 4 ]
for  index, value  in  enumerate(l):
    
print  ( ' %d, %d '   %  (index, value))

 

10 分割字符串且去掉空白

names  =   ' jianpx, yy, mm, , kk '
result 
=  [name  for  name  in  names.split( ' , ' if  name.strip()]

 

11 python中的a?b:c

return_value  =  True  if  a  ==   1   else  False  

 

12 Zen of python

>>>   import  this
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

add  =   lambda  x,y : x  +  y
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。

a = [0, 1 , 2 , 3 , 4 , 5 , 6 , 7 ]
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个元组的列表。

a = [0, 1 , 2 , 3 , 4 , 5 , 6 , 7 ]
=  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和第一个序列元素而不是序列的头两个元素。

import  functools
=  [ 1 , 2 , 3 , 4 , 5 ]
=  functools.reduce( lambda  x,y:x + y,a)
print (s)
# 15

 

17 range用来返回一个list

strings  =  [ ' a ' ' b ' ' c ' ' d ' ' e ' ]
for  index  in  range(len(strings)):
    
print  (index)
#  prints '0 1 2 3 4'

 

18 all用来检查list中所有的元素都满足一定的条件

numbers  =  [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
if  all(number  <   10   for  number  in  numbers):
    
print  ( " Success! " )
#  Output: 'Success!'

 

19 any用来检查list中是否至少由一个元素满足一定的条件

numbers  =  [ 1 , 10 , 100 , 1000 , 10000 ]
if  any(number  <  0  for  number  in  numbers):
    
print  ( ' Success! ' )
else :
    
print ( ' Fail! ' )
#  Output: 'Fail!'

 

20 使用set来检查list是否有重复的元素

numbers  =  [ 1 , 2 , 3 , 3 , 4 , 1 ]
if  len(numbers)  ==  len(set(numbers)):
    
print  ( ' List is unique! ' )
#  In this case, doesn't print anything

 

21 从已有的dict构造新的dict

emails  =  { ' Dick ' ' [email protected] ' ' Jane ' ' [email protected] ' ' Stou ' ' [email protected] ' }
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  =  True
#  test = False
result  =  test  and   ' Test is True '   or   ' Test is False '
print (result)
#  result is now 'Test is True'

 

23 检查字符串是否包含子字符串 

string  =   ' Hi there '   #  True example
#
 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

numbers  =  ( 1 , 2 , 3 , 4 , 5 #  Since we're going for efficiency, I'm using a tuple instead of a 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

 

完! 

 

你可能感兴趣的:(python)