设为首页 收藏本站
查看: 1038|回复: 0

[经验分享] python技巧31[pythonTips1]

[复制链接]

尚未签到

发表于 2015-4-20 11:18:20 | 显示全部楼层 |阅读模式
  
  1 使用%来格式字符串


print("hello %s : %s" % ("AAA", "you are so nice"))  
  2 使用zip来将两个list构造为一个dict


names = ['jianpx', 'yue']   
ages = [23, 40]   
m = 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


d = {1:"v1", 2:"v2"}
if 1 in d.keys():
  print("d dict has the key 1")  
  6 使用set来去除list中的重复元素


l = [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


l = [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]
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和第一个序列元素而不是序列的头两个元素。


import functools
a = [1,2,3,4,5]
s = 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': 'bob@example.com', 'Jane': 'jane@example.com', 'Stou': 'stou@example.net'}
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
  
  完!
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-58771-1-1.html 上篇帖子: python学习入门 下篇帖子: Python之美--Decorator深入详解(一)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表