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
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
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'}
问题 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
例子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
print a, b, c >>> a = ("l", "M", "n") >>> Fun(a[0], a[1], a[2]) l M n >>> apply(Fun, a) l M n >>>
>>>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]
>>>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]
>>>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
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'
import filecmp filecmp.cmp(r'e:\1.txt',r'e:\2.txt')
如果两个文件相同,会输出True,否则会输出false。
也许你需要根据特定的参数动态的生成某个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.')
class MyClass: ... @classmethod # classmethod的修饰符 def class_method(cls, arg1, arg2, ...): ... @staticmethod # staticmethod的修饰符 def static_method(arg1, arg2, ...): ...13.
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)]
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
from collections import defaultdict persons_by_age = defaultdict(list) for person in persons: persons_by_age[person.age].append(person)
>>> [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'