0
1
0
1. 云栖社区>
2. 博客>
3. 正文

鲜为人知的 Python 语法

http://python.jobbole.com/89252/

def f():

x = 'string'

if x.endswith('g'):

x = x[:-1]

r = ''

for i in xrange(len(x)):

if x[i] != 'i':

r += x[i]

return r

f()

-> 'strn'

(lambda: ([x for x in ['string']], x.endswith('g') and [x for x in [x[:-1]]], [r for r in ['']], [x[i] != 'i' and [r for r in [r+x[i]]] for i in xrange(len(x))], r)[-1])()

-> 'strn'

b if a else c

(a and [b] or [c])[0]

(b, c)[not a]

a and b or c

True and [] or [1] -> [1], but: [] if True else [1] -> []

1.在原字符串中和上一个字符比较：

''.join(['' if i and j == x[i-1] else j for i,j in enumerate(x)]

2.把前一个字符保存到临时变量中：

''.join([('' if i == a else i, [a for a in [i]])[0] for a in [''] for i in x])

''.join([('' if i == a.pop() else i, a.append(i))[0] for a in [['']] for i in x])

3.在新字符串中和上一个字符比较：

[(not r.endswith(i) and [r for r in [r+i]], r)[-1] for r in [''] for i in x][-1]

4.通过 reduce 函数和 lambda 表达式：

reduce(lambda a, b: a if a.endswith(b) else a + b, x)

1.把中间值保存在列表中

[(lambda: (l[-1], l.append(l[-1] + l[-2]))[0])() for l in [[1, 1]] for x in xrange(19)]

[(l[-1], l.append(l[-1] + l[-2]))[0] for l in [[1, 1]] for x in xrange(19)]

2.把中间值保存到字典中:

[i for x in [(lambda: (l['a'], l.update({'a': l['a'] + l['b']}), l['b'], l.update({'b': l['a'] + l['b']}))[::2])() for l in [{'a': 1, 'b': 1}] for x in xrange(10)] for i in x]

[i for x in [(l['a'], l.update({'a': l['a'] + l['b']}), l['b'], l.update({'b': l['a'] + l['b']}))[::2] for l in [{'a': 1, 'b': 1}] for x in xrange(10)] for i in x]

3.通过 reduce 函数和 lambda 表达式：

reduce(lambda a, b: a + [a[-1] + a[-2]], xrange(10), [1, 1])

reduce(lambda a, b: a.append(a[-1] + a[-2]) or a, xrange(10), [1, 1])

4.速度最快的变体：

[l.append(l[-1] + l[-2]) or l for l in [[1, 1]] for x in xrange(10)][0]

[a.append(b) for a in [[None]] for b in a]

1.复制列表：

l = [1, 2, 3]

m = l[:]

m

-> [1, 2, 3]

2.移除/替换 列表中的任意元素：

l = [1, 2, 3]

l[1:-1] = [4, 5, 6, 7]

l

-> [1, 4, 5, 6, 7, 3]

3.在列表的开头添加元素：

l = [1, 2, 3]

l[:0] = [4, 5, 6]

l

-> [4, 5, 6, 1, 2, 3]

4.在列表的尾部添加元素：

l = [1, 2, 3]

l[-1:] = [l[-1], 4, 5, 6]

l

-> [1, 2, 3, 4, 5, 6]

5.反转列表：

l = [1, 2, 3]

l[:] = l[::-1]

Python 阻止替换类实例中的方法，因为 python 给类实例中的方法赋予了只读属性：

class A(object):

def x(self):

print "hello"

a = A()

def y(self):

print "world"

a.x.im_func = y

a.x.im_func.func_code = y.func_code

a.x()

-> 'world'

new_a = A()

new_a.x()

-> 'world'

1.阶乘函数：

def f(n, c={}):

if n in c:

return c[n]

if (n < 2):

r = 1

else:

r = n * f(n - 1)

c[n] = r

return r

f(10)

-> 3628800

f.func_defaults

({1: 1,

2: 2,

3: 6,

4: 24,

5: 120,

6: 720,

7: 5040,

8: 40320,

9: 362880,

10: 3628800},)

2.斐波拉契数列：

def fib(n, c={}):

if n in c:

return c[n]

if (n < 2):

r = 1

else:

r = fib(n - 2) + fib(n - 1)

c[n] = r

return r

fib(10)

-> 89

fib.func_defaults[0].values()

-> [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

+ 关注

corcosa 8693人浏览