Python Efficient programming Skills _python

Source: Internet
Author: User
The following tips I've picked out are often overlooked, but they can actually help us a lot in everyday programming.

1. Dictionary derivation (Dictionary comprehensions) and set derivation (set comprehensions)
Most Python programmers know and use list derivation (comprehensions). If you're not familiar with the list comprehensions concept-a list comprehension is a shorter, simpler way to create a list.

>>> some_list = [1, 2, 3, 4, 5]
>>> another_list = [x + 1 for x in Some_list]
>>> another_list
[2, 3, 4, 5, 6]

Since Python 3.1 (or even Python 2.7), we can create collections and dictionary tables with the same syntax:
Copy Code code as follows:

>>> # Set Comprehensions
>>> some_list = [1, 2, 3, 4, 5, 2, 5, 1, 4, 8]
>>> Even_set = {x for x in Some_list if x% 2 = 0}
>>> Even_set
Set ([8, 2, 4])
>>> # Dict Comprehensions
>>> d = {x:x% 2 = 0 for x in range (1, 11)}
>>> D
{1:false, 2:true, 3:false, 4:true, 5:false, 6:true, 7:false, 8:true, 9:false, 10:true}

In the first example, we create a set with a SOME_LIST element based on the base, and the collection contains only even numbers. And in the dictionary example, we created a key that is not repeating an integer between 1 and 10, and value is a Boolean that indicates whether the key is an even number.
Another notable thing here is the literal representation of the collection. We can simply create a set in this way:
Copy Code code as follows:

>>> My_set = {1, 2, 1, 2, 3, 4}
>>> My_set
Set ([1, 2, 3, 4])

You do not need to use the built-in function set ().

2. Use the counter Count object when counting.
It sounds obvious, but it is often forgotten. For most programmers, a few things are a common task, and in most cases it's not challenging-there are several ways to do this more easily.
Python's collections Class library has a subclass of the built-in Dict class that specializes in this kind of thing:
Copy Code code as follows:

>>> from collections Import Counter
>>> C = Counter (' Hello World ')
>>> C
Counter ({' L ': 3, ' O ': 2, ': 1, ' E ': 1, ' d ': 1, ' H ': 1, ' R ': 1, ' W ': 1})
>>> C.most_common (2)
[(' L ', 3], (' O ', 2)]

3. Pretty print out JSON
JSON is a very good form of data serialization, and is heavily used by today's various APIs and Web service. Using Python's built-in JSON processing makes the JSON string somewhat readable, but when it comes to large data, it behaves like a long, contiguous line, and the human eye is hard to watch.
To make the JSON data more user-friendly, we can use the indent parameter to output beautiful JSON. This is especially useful when you are programming interactively or logging on the console:
Copy Code code as follows:

>>> Import JSON
>>> Print (json.dumps (data)) # No Indention
{' Status ': ' OK ', ' count ': 2, ' results ': [{' Age ':], ' name ': ' Oz ', ' lactose_intolerant ': true}, {' Age ': ', ' name ': ' Joe ', ' Lactose_intolerant ': false}]}
>>> Print (Json.dumps (data, indent=2)) # with Indention
{
"Status": "OK",
"Count": 2,
"Results": [
{
"Age": 27,
"Name": "Oz",
' Lactose_intolerant ': true
},
{
"Age": 29,
"Name": "Joe",
"Lactose_intolerant": false
}
]
}

Also, using the built-in Pprint module, you can make everything else print out more beautifully.

4. Create a one-time, fast, small Web service
Sometimes we need to do some simple, basic rpc-like interactions between two machines or services. We want to use the B program in a simple way to call one of the methods in a program-sometimes on another machine. Internal use only.
I do not encourage the use of the methods described here in a non internal, one-off programming. We can do this by using a protocol called XML-RPC (which corresponds to this Python library).
Here is an example of using the Simplexmlrpcserver module to create a fast, small file-reading server:
Copy Code code as follows:

From Simplexmlrpcserver import Simplexmlrpcserver

def file_reader (file_name):
With open (file_name, ' R ') as F:
Return F.read ()

Server = Simplexmlrpcserver (' localhost ', 8000)
Server.register_introspection_functions ()
Server.register_function (File_reader)
Server.serve_forever ()

Client:
Copy Code code as follows:

Import Xmlrpclib
Proxy = Xmlrpclib. Serverproxy (' http://localhost:8000/')
Proxy.file_reader ('/tmp/secret.txt ')


So we get a remote file-reading tool, no external dependencies, just a few code (of course, no security, so you can only do this at home).

5. Python's Magical open source community
A few of the things I mentioned here are in the Python standard library, and if you have Python installed, you can already use it. For many other types of tasks, there are a large number of community-maintained Third-party libraries for you to use.
The following list is what I think is necessary for a good and robust open Source library:

A good open Source library must ...

• Contains a very clear license statement that can be applied to your usage scenarios.
• Development and maintenance work is very active (or, you can participate in developing and maintaining it.) )
• Simple to use PIP installation or iterative deployment.
• There are test suites with sufficient test coverage.
If you find a good library that meets your requirements, don't be embarrassed ———— most open source projects are welcome to donate code and welcome help-even if you're not a Python whiz.

Original: http://www.aqee.net/improving-your-python-productivity/

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.