python31技巧[pythonTips1]
时间:2011-01-13 来源:iTech
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 thisThe 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!
>>>
完!
相关阅读 更多 +