Python Efficient Programming Tips

Source: Internet
Author: User
Some of the techniques I've picked out below are often overlooked, but they can really help us in everyday programming.

1. Dictionary derivation (Dictionary comprehensions) and set derivation (set comprehensions)
Most Python programmers know and use list comprehensions. If you are not familiar with the list comprehensions concept-a list comprehension is a shorter, more concise 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 use the same syntax to create collections and dictionary tables:
Copy CodeThe code is 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 created a collection with non-repeating elements based on some_list, and the set contains only an even number. In the case of the dictionary table, we create a key that is 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 collection of literal representations. We can simply create a collection in this way:
Copy CodeThe code is 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.
This may sound obvious, but it is often forgotten. For most programmers, counting one thing is a very common task, and in most cases it is not a very challenging thing-there are several ways to accomplish this task more simply.
The Collections class library in Python has a subclass of the built-in Dict class that is specifically designed to do this kind of thing:
Copy CodeThe code is 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. Beautiful print out JSON
JSON is a very good form of data serialization that is used by many of today's 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 as a long, contiguous line, and the human eye is hard to see.
In order 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 in the console:
Copy CodeThe code is 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 the printout of anything else more beautiful.

4. Create a one-time, fast, small Web service
Sometimes, we need to do some simple, very basic RPC interaction between two machines or services. We want to use a simple way of using the B program to invoke a method in a program--sometimes on another machine. Internal use only.
I do not encourage the methods described here to be used in non-internal, one-time programming. We can do this with a protocol called XML-RPC, which corresponds to this Python library.
Here is an example of using the Simplexmlrpcserver module to build a fast, small file read server:
Copy CodeThe code is 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 CodeThe code is as follows:


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



We've got a remote file-reading tool with no external dependencies, just a few lines of code (of course, no security, so you can do it at home).

5. Python's Magical open source community
A few of the things I've 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 number of community-maintained third-party libraries available for you to use.
The following checklist is an essential requirement for what I think is a good and robust open Source library:

A good open Source library must ...

• Contains a clear license statement that can be applied to your usage scenarios.
• Development and maintenance work is very active (or, you can participate in development to maintain it.) )
• Simple to use Pip to install or deploy repeatedly.
• There is a test suite with sufficient test coverage.
If you find a good library that meets your requirements, don't be embarrassed ———— most of the open source projects welcome the donation code and welcome help-even if you are not a Python master.

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.