A detailed example of Python's elegant techniques

Source: Internet
Author: User


Enumeration

Don't do this:

i = 0
For item in Iterable:
Print I, item
i + 1

But this:

For I, item in enumerate (iterable):
Print I, item

Enumerate can accept a second parameter, for example:

>>> List (Enumerate (' abc '))
[(0, ' a '), (1, ' B '), (2, ' C ')]
>>> List (Enumerate (' abc ', 1))
[(1, ' a '), (2, ' B '), (3, ' C ')]

Dictionary/Set parsing

You may know list parsing, but don't know dictionary/set parsing. Dictionary/Set parsing is simple and efficient, for example:

My_dict = {I:I * I for I in Xrange (100)}
My_set = {I * for i in xrange (100)}
# There is only a difference of ': ' in both

Force floating-point number Division
If we divide by an integer, even if the result is a floating-point number, Python (2) will still give us an integer. To circumvent this problem, we need to do this:

result = 1.0/2

But now there is a different way to solve this problem, even before I did not realize that there is such a method exists. You can do the following:

From __future__ Import Division
result = 1/2
# Print (Result)
# 0.5

It should be noted that this tip applies only to Python 2. The import operation is not required in Python 3 because it has been import by default.

A simple server

Do you want to quickly and easily share files under the directory? You can do this:

# Python2
Python-m Simplehttpserver
# Python 3
Python3-m Http.server

This time to start a server

Python expression evaluation

We all know Eval, but maybe not everyone knows literal_eval. You can do this:

Import AST
My_list = Ast.literal_eval (expr)

Rather than this:

expr = "[1, 2, 3]"
My_list = eval (expr)

I believe this is the first time for most people to see this form, but in fact this has been in Python for a long time.

Profiling scripts

Run the script in the following way, and you can easily analyze it:

Python-m CProfile my_script.py

Object Self Test

In Python, you can check for objects by Dir (), for example:

>>> foo = [1, 2, 3, 4]
>>> dir (foo)
[' __add__ ', ' __class__ ', ' __contains__ ',
' __delattr__ ', ' __delitem__ ', ' __delslice__ ', ...,
' Extend ', ' index ', ' Insert ', ' pop ', ' Remove ',
' Reverse ', ' sort ']

Debug scripts

You can use the PDB module to set breakpoints in the script to debug the script, just like this:

Import PDB
Pdb.set_trace ()

You can add pdb.set_trace () anywhere in the script, and the function will set a breakpoint in that position. Super convenient. You should read more about the PDB function, because there are a lot of little-known features in it.

Simplifying If structure

If you must check some values, you can use the


if n in [1,4,5,6]:

Rather than using a complex if structure:

If N==1 or n==4 or n==5 or n==6:

string/Sequence Reverse

The following way to quickly reverse a list:

>>> a = [1,2,3,4]
>>> A[::-1]
[4, 3, 2, 1]
# This creates a new reversed list.
# If you are want to reverse a list and can do:
A.reverse ()
This approach also applies to strings:

>>> foo = "Yasoob"
>>> Foo[::-1]
' Boosay '

To print gracefully

The following way you can print dictionaries and lists in an elegant way:

From Pprint import Pprint
Pprint (my_dict)

This is very efficient for dictionary printing, so if you want to print out JSON quickly and gracefully from a file, you can do this:

Cat File.json | Python-m Json.tools

Ternary operation

Ternary operation is a fast operation of If-else statement, also known as conditional operation. Here are a few examples for you to refer to:

[On_true] if [expression] else [on_false]
X, y = 50, 25
small = x if x < y else y

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.