1. You want to swap the values of some variables, but you don't want to use a temporary variable
a, b, c = b, c, a
2. You'd like to construct a dictionary without having to quote the keys.
def makedict(**kwargs): return kwargs data = makedict(red=1, green=2, blue=3) d = dict(red=1, green=2, blue=3)
3. Given two dictionaries, you need to find the set of keys that are in both dictionaries.
some_dict = { 'zope':'zzz', 'python':'rocks' } another_dict = { 'python':'rocks', 'perl':'} print 'Intersects:', [x for x in some_dict if another_dict.has_key(x)] print 'Intersects:', filter(another_dict.has_key, some_dict.keys())性能对比:
print '################################性能测试############################' import time def timeo(fun, n=1000): start = time.clock() for i in range(n):fun() stend = time.clock() thetime = stend - start return fun.__name__, thetime to500 = {} for i in range(500):to500[i] = 1 evens = {} for i in range(0, 1000, 2):evens[i] = 1 def simpleway(): result = [] for k in to500.keys(): if evens.has_key(k): result.append(k) return result def pyth22way(): return [k for k in to500 if k in evens] def filterway(): return filter(evens.has_key, to500.keys()) def badsloway(): result = [] for k in to500.keys(): if k in evens.keys(): result.append(k) return result for f in simpleway, pyth22way, filterway, badsloway: print '%s: %.5f' % timeo(f)################################性能测试############################
badsloway: 5.78203
合并字典键
def union_keys(some_dict, another_dict): temp_dict = some_dict.copy() temp_dict.update(another_dict) return temp_dictupdate函数说明:
D.update(E, **F) -> None. Update D from E and F: for k in E: D
[k] = E[k]
(if E has keys else: for (k, v) in E: D[k] = v) then: for k in F: D[k] =
F[k]
4. Using List Comprehensions Instead of map and filter
thenewlist = [x + 23 for x in theoldlist] thenewlist = [x for x in theoldlist if x > 5] thenewlist = [x + 23 for x in theoldlist if x > 5]5. You need an arithmetic progression, just like the built-in function range, but with float values ( range works only on integers).
def myrange(start, end=None, inc=1.0): if end == None: end = start + 0.0 start = 0.0 L = [] while True: next = len(L) * inc + start if inc > 0 and next >= end: break elif inc < 0 and next <= end: break L.append(next) return L mr = myrange(10.0) print mr mr1 = myrange(2, 9) print mr1