Little-known Python syntax

Source: Internet
Author: User

Everyone (well, not everyone) knows Python is a wide-ranging, easy-to-read programming language that is easy to get started with.

But at the same time Python syntax allows us to do some very strange things.

Overriding a multiline function with a lambda expression

Python's lambda expressions are known to not support multiple lines of code. But you can simulate the effect of multiple lines of code.

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 '

Although it may seem strange, the above function can be replaced with the following lambda expression function:

(Lambda: ([x for X in [' String ']], X.endswith (' G ') and [x for x in [X[:-1]]], [R to R in [']], [x[i]! = ' I ' and [R for R] In [R+x[i]] "For I in Xrange (len (x))], R) [-1]) ()

' Strn '

Never write code like this in a production environment:)

Ternary operators

Modern Python provides a simpler syntax:

b If a else C

You can also rewrite it in the following ways:

(A and [b] or [C]) [0]

(b, C) [Not a]

By the way, the following variant is wrong:

A and B or C

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

Remove duplicate elements from a list deduction

Let's convert the string x = ' Tteesstt ' to ' test '.

1. Compare the previous character in the original string:

'. Join ([' if I and j = = X[i-1] Else J for I,j in Enumerate (x)]

2. Save the previous character to a temporary variable:

". Join ([" If i = = a else I, [a for a] [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. In the new string and the previous character comparison:

[(Not R.endswith (i) and [R for R] [R+i]], R) [-1] for R in ["] for I in X] [-1]

4. Through the reduce function and the lambda expression:

Reduce (lambda A, b:a if A.endswith (b) Else A + B, x)

Fibonacci sequence obtained by list derivation

1. Save the middle value in the list

[(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. Save the middle value in the dictionary:

[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 I n [{' A ': 1, ' B ': 1}] for x in Xrange (Ten)] 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 (Ten)] for I in X]

3. Through the reduce function and the lambda expression:

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. The fastest variant:

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

Using a list derivation to generate a dead loop

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

List Slicing Tips

1. Copy the list:

L = [1, 2, 3]

m = l[:]

M

, [1, 2, 3]

2. Remove/Replace any of the elements in the list:

L = [1, 2, 3]

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

L

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

3. Add elements at the beginning of the list:

L = [1, 2, 3]

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

L

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

4. Add elements at the end of the list:

L = [1, 2, 3]

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

L

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

5. Reverse the list:

L = [1, 2, 3]

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

Replacement method Bytecode

Python prevents the substitution of methods in class instances, because Python gives a read-only attribute to a method in a class instance:

Class A (object):

def x (self):

print "Hello"

A = A ()

Def y (self):

Print "World"

A.x.im_func = y

Typeerror:readonly attribute

However, you can replace it at the byte-code level:

A.x.im_func.func_code = Y.func_code

A.x ()

' World '

Attention! This affects not only the current instance, but also the entire class (exactly the function that binds to the class) (The translator notes: This should be a clerical error, presumably the author's intention is to say exactly all classes that are bound to this function), and all other instances will be affected:

New_a = A ()

New_a.x ()

' World '

Make a mutable element the default value for a function parameter

It is dangerous to use mutable objects as default values for function parameters, and there are a lot of tricky interview questions in the interview. But this is very helpful for caching mechanisms.

1. Factorial function:

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:5,040,

8:40,320,

9:362,880,

10:3.6288 million},)

2. Fibonacci Sequence:

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]

Like friends can add QQ group 813622576, the group has free information for everyone to Exchange learning Oh!!!!

Little-known Python syntax

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.