Python一点一点学习中。。。
声明:
本文部分内容Copy自大牛们的博客下面会列出:
3 4 5 6 7 8 9 10==>http://harmony.relax.blogbus.com/logs/12303417.html
12 ====>http://my.chinaunix.net/space.php?uid=1721137&do=blog&id=274710
http://linuxtoy.org/archives/python-collection-tips.html
更多tips,http://www.siafoo.net/article/52
1. 条件选择and or
用过C的想必都对(a>1)?1:2 这样的表达式情有独钟,Python里边应该怎么做呢?In [15]: True and 1 or 2
Out[15]: 1
In [16]: False and 1 or 2
Out[16]: 2
还有一种情况是,你经常需要写这样的代码: if( a ) c = a else c = b;
如何用python表达呢: c = a or b
In [10]: a = 0
In [11]: b = 1
In [12]: c = a or b
In [13]: c
Out[13]: 1
那么and呢
In [1]: a= 1 and 2
In [2]: a
Out[2]: 2
In [3]: a = 1 or 2
In [4]: a
Out[4]: 1
In [5]: a = 1 and 0
In [6]: a
Out[6]: 0
2. zip + dict
In [17]: a = "ABCD"
In [18]: b = "abcd"
In [19]: zip(a,b)
Out[19]: [('A', 'a'), ('B', 'b'), ('C', 'c'), ('D', 'd')]
In [20]: dict(zip(a,b))
Out[20]: {'A': 'a', 'B': 'b', 'C': 'c', 'D': 'd'}
3. * and **
问题
Python的函数定义中有两种特殊的情况,即出现*,**的形式。
如:def myfun1(username, *keys)或def myfun2(username, **keys)等。
* 用来传递任意个无名字参数,这些参数会一个Tuple的形式访问。
**用来处理传递任意个有名字的参数,这些参数用dict来访问。*
应用:
#########################
# “*” 的应用
#########################
>>> def fun1(*keys):
... print "keys type=%s" % type(keys)
... print "keys=%s" % str(keys)
... for i in range(0, len(keys)):
... print "keys[" + str(i) + "]=%s" % str(keys[i])
...
>>> fun1(2,3,4,5)
输出以下结果:
keys type=<type 'tuple'>
keys=(2, 3, 4, 5)
keys[0]=2
keys[1]=3
keys[2]=4
keys[3]=5
#########################
# “**” 的应用
#########################
>>> def fun2(**keys):
... print "keys type=%s" % type(keys)
... print "keys=%s" % str(keys)
... print "name=%s" % str(keys['name'])
...
>>>
>>> fun2(name="vp", age=19)
输出以下结果:
keys type=<type 'dict'>
keys={'age': 19, 'name': 'vp'}
name=vp
4、 Lambda 形式
出于适当的需要,有几种通常在功能性语言和Lisp中出现的功能加入到了Python。通过lambda关键字,可以创建很小的匿名函数。这里有一个函数返回它的两个参数的和:“lambda a, b: a+b”。 Lambda 形式可以用于任何需要的函数对象。出于语法限制,它们只能有一个单独的表达式。语义上讲,它们只是普通函数定义中的一个语法技巧。类似于嵌套函数定义,lambda形式可以从包含范围内引用变量:语法: lambda argument1, argument2,... argumentN :
例子1:
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
例子2:
>>> f = lambda x, y, z: x + y + z
>>> f(2, 3, 4)
9
5、apply
Python 提供了一个内置函数 apply() 来简化函数调用。>>> def Fun(a, b, c): print a, b, c
>>> a = ("l", "M", "n")
>>> Fun(a[0], a[1], a[2])
l M n
>>> apply(Fun, a)
l M n
>>>
6、 filter()函数
filter()函数包括两个参数,分别是function和list。该函数根据function参数返回的结果是否为真来过滤list参数中的项,最后返回一个新列表,如下例所示: >>>a=[1,2,3,4,5,6,7]
>>>b=filter(lambda x:x>5, a)
>>>print b
>>>[6,7]
如果filter参数值为None,就使用identity()函数,list参数中所有为假的元素都将被删除。如下所示:
>>>a=[0,1,2,3,4,5,6,7]
b=filter(None, a)
>>>print b
>>>[1,2,3,4,5,6,7]
7、 map()函数
map()的两个参数一个是函数名,另一个是列表或元组。 >>>map(lambda x:x+3, a) #这里的a同上
>>>[3,4,5,6,7,8,9,10]
#另一个例子
>>>a=[1,2,3]
>>>b=[4,5,6]
>>>map(lambda x,y:x+y, a,b)
>>>[5,7,9]
8 、 reduce()函数
reduce 函数可以按照给定的方法把输入参数中上序列缩减为单个的值,具体的做法如下:首先从序列中去除头两个元素并把它传递到那个二元函数中去,求出一个值,再把这个加到序列中循环求下一个值,直到最后一个值 。 >>>reduce(lambda x,y:x*y, [1,2,3,4,5]#((((1*2)*3)*4)*5
>>>120
>>>reduce(lambda x,y:x*y, [1,2,3], 10)
>>>60 #((1*2)*3)*10
9. UserString
Python中字符串是Inmutable的,也就是说是不可变的,所有不能写a[0]='a' 这样的C语句,但是UserString 这个模块提供了这个特性。 In [1]: import UserString
In [2]: a = UserString.MutableString('c'*30)
In [3]: a
Out[3]: 'cccccccccccccccccccccccccccccc'
In [4]: a[0] = 'A'
In [5]: a
Out[5]: 'Accccccccccccccccccccccccccccc'
10 , Python Tips : 判断两个文件是否相同
python中提供了很便捷的方法来判断两个文件的内容是否相同,只要两行代码:import filecmp
filecmp.cmp(r'e:\1.txt',r'e:\2.txt')
如果两个文件相同,会输出True,否则会输出false。
11 . 动态生成对象
也许你需要根据特定的参数动态的生成某个class的实例,你需要写一堆变态的if else吗,不需要。
#!/usr/bin/env python
#--*-- encoding:utf-8 --*--
class MyDynamicClass:
def say_hello(self, name):
print "hello", name
def create_dynamic_cls(cls):
return globals()[cls]()
a = create_dynamic_cls('MyDynamicClass')
a.say_hello('Tom.')
12. @classmethod VS @staticmethod
13.class MyClass: ... @classmethod # classmethod的修饰符 def class_method(cls, arg1, arg2, ...): ... @staticmethod # staticmethod的修饰符 def static_method(arg1, arg2, ...): ...
- exefile("filename.py")
- 直接在交互式命令行执行,所有的表量很状态都会保存,适合调试使用。
13.
判断一个 list 是否为空
传统的方式:
if len(mylist):
# Do something with my list
else:
# The list is empty
由于一个空 list 本身等同于 False,所以可以直接:
if mylist:
# Do something with my list
else:
# The list is empty
13.
遍历 list 的同时获取索引 传统的方式: i = 0 for element in mylist: # Do something with i and element i += 1 这样更简洁些: for i, element in enumerate(mylist): # Do something with i and element pass
14.
list 排序
在包含某元素的列表中依据某个属性排序是一个很常见的操作。例如这里我们先创建一个包含 person 的 list:
class Person(object):
def __init__(self, age):
self.age = age
jj传统的方式是:
def get_sort_key(element):
return element.age
for element in sorted(persons, key=get_sort_key):
print "Age:", element.age
更加简洁、可读性更好的方法是使用 Python 标准库中的 operator 模块:
from operator import attrgetter
for element in sorted(persons, key=attrgetter('age')):
print "Age:", element.age
attrgetter
方法优先返回读取的属性值作为参数传递给 sorted
方法。operator
模块还包括 itemgetter
和 methodcaller
方法,作用如其字面含义。
15. 在 Dictionary 中元素分组
和上面类似,先创建 Persons:
class Person(object):
def __init__(self, age):
self.age = age
persons = [Person(age) for age in (78, 14, 78, 42, 14)]
如果现在我们要按照年龄分组的话,一种方法是使用 in 操作符:
persons_by_age = {}
for person in persons:
age = person.age
if age in persons_by_age:
persons_by_age[age].append(person)
else:
persons_by_age[age] = [person]
assert len(persons_by_age[78]) == 2
相比较之下,使用 collections 模块中 defaultdict 方法的途径可读性更好:
from collections import defaultdict
persons_by_age = defaultdict(list)
for person in persons:
persons_by_age[person.age].append(person)
defaultdict 将会利用接受的参数为每个不存在的 key 创建对应的值,这里我们传递的是 list,所以它将为每个 key 创建一个 list 类型的值。
16: list comprehethion
>>> [i for i in a if i % 2 == 0]
[2, 4, 6]
>>> [i * i for i in a if i % 2 == 0]
[4, 16, 36]
>>> {i * i: 1 for i in a if i % 2 == 0}
{16: 1, 36: 1, 4: 1}
17 检查字符串是否是另一个的字串
string = 'Hi there' # True example
2# string = 'Good bye' # False example
3if 'Hi' in string:
4 print 'Success!'
18 reload测试
import test
>>> test.answer_to_life_the_universe_and_everything 54 >>> # Whoops that's not right, I'd better edit the module.... ... >>> reload(test) >>> test.answer_to_life_the_universe_and_everything
19 pading
>>> n = '4'
>>> print n.zfill(3)
>>> '004'
And for numbers:
>>> n = 4
>>> print '%03d' % n
>>> '004'