& Lt; Convert & gt; elegant Python skills and python skills

Source: Internet
Author: User
Tags iterable pprint

<> Elegant and elegant Python skills
Enumeration

Do not do this:

Select All Copy Put in notes
i = 0 for item in iterable:     print i, item     i += 1

But like this:

Select All Copy Put in notes
for i, item in enumerate(iterable):    print i, item

Enumerate can accept the second parameter, for example:

Select All Copy Put in notes
>>> 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 resolution, but you do not know the dictionary/set resolution. Dictionary/set Parsing is simple and efficient, for example:

Select All Copy Put in notes
my_dict = {i: i * i for i in xrange(100)} my_set = {i * 15 for i in xrange(100)}# There is only a difference of ':' in both
Force floating point Division

If we divide it by an integer, Python (2) still gives us an integer even if the result is a floating point number. To avoid this problem, we need to do this:

Select All Copy Put in notes
result = 1.0/2

But now there is another way to solve this problem, even before I realized that this method exists. You can perform the following operations:

Select All Copy Put in notes
from __future__ import division result = 1/2# print(result)# 0.5

Note that this tip only applies to Python 2. In Python 3, the import operation is not required because it has been imported by default.

Simple Server

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

Select All Copy Put in notes
# Python2python -m SimpleHTTPServer# Python 3python3 -m http.server

Start a server this time

Evaluate Python expressions

We all knowevalBut maybe not everyone knowsliteral_eval. You can do this:

Select All Copy Put in notes
import ast my_list = ast.literal_eval(expr)

Instead:

Select All Copy Put in notes
expr = "[1, 2, 3]" my_list = eval(expr)

I believe this is the first time that most people have seen it, but it has been in Python for a long time.

Analysis script

Run the script in the following way to analyze it easily:

Select All Copy Put in notes
python -m cProfile my_script.py
Object self-check

In Python, you can use dir () to check objects, for example:

Select All Copy Put in notes
>>> foo = [1, 2, 3, 4]>>> dir(foo) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', ... , 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
Debug scripts

You can usepdbThe module sets a breakpoint in the script to debug the script, as shown in the following figure:

Select All Copy Put in notes
import pdbpdb.set_trace()

You can add any part of the scriptpdb.set_trace(), This function will set a breakpoint at that position. Super convenient. You should read more about the pdb function, because there are many little-known functions in it.

Simplified if Structure

If you must check some values, you can use

Select All Copy Put in notes
if n in [1,4,5,6]:

Instead of using a complex if structure:

Select All Copy Put in notes
if n==1 or n==4 or n==5 or n==6:
String/series in reverse order

The following method can be used to quickly reverse a list:

Select All Copy Put in notes
>>> a = [1,2,3,4]>>> a[::-1][4, 3, 2, 1]# This creates a new reversed list. # If you want to reverse a list in place you can do:a.reverse()

This method also applies to strings:

Select All Copy Put in notes
>>> foo = "yasoob">>> foo[::-1]'boosay'
Print elegantly

The following method can print the dictionary and list in an elegant way:

Select All Copy Put in notes
from pprint import pprint pprint(my_dict)

This is very efficient for dictionary printing. If you want to quickly and elegantly print json from a file, you can do this:

Select All Copy Put in notes
cat file.json | python -m json.tools
Ternary Computation

Ternary operations are quick operations for if-else statements, also known as conditional operations. Here are a few examples for your reference:

Select All Copy Put in notes
[on_true] if [expression] else [on_false]x, y = 50, 25small = x if x < y else y
Http://www.ido321.com/1576.html.

According to @ Nicolas Bevacqua's nifty-python-tricks, the entire translation contains my own understanding and thoughts. If the translation is poor or wrong, ask your colleagues for advice. If you need to reprint this translation, you must specify the English Source: https://freepythontips.wordpress.com/2015/04/19/nifty-python-tricks /.

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.