Python Elegant notation

Source: Internet
Author: User

In this article I will share with you some really useful tips and tricks that you may not have known before. So don't waste your time, let's just take a look at these things:

Enumeration

Before we do this:

1234 =0for item in iterable:    print i, item    +=1

Now let's do this:

12 fori, item in enumerate(iterable):    printi, item

The enumerate function can also receive a second parameter. Just like this:

12345 >>> 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 how to do list parsing, but you may not know the dictionary/collection parsing. They are easy to use and efficient. As in the following example:

123456 my_dict = {i: i * for in xrange(100)}my_set = {i * 15 for in xrange(100)}# There is only a difference of ‘:‘ in both# 两者的区别在于字典推导中有冒号

Force floating-point Division

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

1 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:

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

Look, now you don't need to add ". 0" to the data to get an accurate answer. 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.

Simple server

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

# python2python-m simplehttpserver# Python 3python3-m http.server

This will cause a server to start.

Evaluate a Python expression

We all know the Eval function, but do we know the Literal_eval function? Maybe a lot of people don't know it. You can do this with:

12 importastmy_list =ast.literal_eval(expr)

To replace the following actions:

12 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.

Script Analysis

You can easily run script analysis by running the following code:

1 python -m cProfile my_script.py

Object Self-Test

In Python you can check the object using the Dir () function. As the following example:

123456 >>> foo = [1234]>>> dir(foo)[‘__add__‘‘__class__‘‘__contains__‘,‘__delattr__‘‘__delitem__‘‘__delslice__‘, ... ,‘extend‘‘index‘‘insert‘‘pop‘‘remove‘,‘reverse‘‘sort‘]

Debug scripts

You can easily set breakpoints in your script through the PDB module. As the following example:

12 importpdbpdb.set_trace()

You can add pdb.set_trace () anywhere in the script and the function will set 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.

If structure simplification

If you need to check several values you can use the following methods:

1 ifin[1,4,5,6]:

To replace the following method:

1 ifn==1 or n==4 or n==5 orn==6:

string/Inverse sequence

You can use the following methods to quickly reverse the sequence of columns:

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

This general approach also applies in reverse order of strings:

123 >>> foo ="yasoob">>> foo[::-1]‘boosay‘

Beautifully printed

You can print a dictionary and a series beautifully in the following ways:

12 frompprint importpprintpprint(my_dict)

This approach is more efficient for dictionary printing. In addition, if you want to beautifully print out the JSON document in the file, you can do this in the following way:

1 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 that you can use to make your code more compact and aesthetically pleasing.

123 [on_true] if[expression] else [on_false]x, y = 5025small = if x < y elsey

That's all that's in today's content. I hope you enjoy this article and you can learn one or two tricks from this article for later use. We'll see you next article. For more information, please follow our Facebook and twitter!

Python Elegant notation

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.