Python Elegance Tips

Source: Internet
Author: User
Tags iterable pprint

Enumeration

Don't do this:

0foritemin iterable:     item     1

But this:

foritemin enumerate(iterable):    item

Enumerate can accept the 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 the list parsing, but not the dictionary/collection parsing. Dictionary/Set parsing is simple and efficient, for example:

forin xrange(10015forin xrange(100is‘:‘in both
Force floating-point 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 there is one other way to solve this problem, even before I realized that there was a way to do so. You can do the following:

fromimport1/2# print(result)# 0.5

It is important to note that this trick is only available for Python 2. The import operation is not required in Python 3 because it has already been import by default.

A simple server

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

# Python2python -m SimpleHTTPServer# Python 3python3 -m http.server

This time 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 it has been around for a long time in Python.

Parsing scripts

Run the script as follows, which can be easily analyzed:

python -m cProfile my_script.py
Object Self-Test

In Python, you can examine objects through Dir (), for example:

>>> foo = [1234]>>> 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 pdbpdb.set_trace()

You can join anywhere in the script where pdb.set_trace() the function sets a breakpoint at that location. Super convenient. You should read more about the PDB function, because there are a lot of little-known features in it.

Simplifying the IF structure

If you have to check some values, you can use the

ifin [1,4,5,6]:

Instead of using complex if structures:

if n==1or n==4or n==5or n==6:
string/Inverse sequence

The following way can quickly reverse a list:

>>> a = [1,2,3,4]>>> a[::-1][4321newIftoreverseindo:a.reverse()

The same approach applies to strings:

>>> "yasoob">>> foo[::-1]‘boosay‘
Print elegantly

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

fromimport 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 operations

A ternary operation is a shortcut to a If-else statement, also known as a conditional operation. Here are a few examples for you to refer to:

[on_trueifelse [on_false5025ifelse y

Source: http://www.ido321.com/1576.html

This article according to @nicolas Bevacqua's "nifty-python-tricks" translation, the entire translation with my own understanding and thought, if the translation is not good or has the wrong place also invites the colleague friend to instruct. If you want to reprint this translation, please specify the English source: https://freepythontips.wordpress.com/2015/04/19/nifty-python-tricks/.

Python Elegance Tips

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.