I have been using Python for many years to introduce Python's efficient programming skills. even today, I am still amazed at the cleanliness of the code and the applicability of DRY programming principles. Over the years, I have learned a lot of tips and knowledge, most of which are obtained by reading popular open-source software such as Django, Flask, and Requests.
The skills I picked below are often ignored, but they can really help us in daily programming.
1. Dictionary comprehensions and Set comprehensions)
Most Python programmers know and use list comprehensions ). If you are not familiar with the concept of list comprehensions, a list comprehension is a more brief and concise method for creating 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 a set and dictionary table:
>>> # 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_setset([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, a set with non-repeating elements is created based on some_list, and the set contains only an even number. In the dictionary table example, we create an integer between 1 and 10 with no duplicate keys and a Boolean value to indicate whether the key is an even number.
Another noteworthy thing here is the literal representation of the set. We can simply use this method to create a set:
>>> my_set = {1, 2, 1, 2, 3, 4}>>> my_setset([1, 2, 3, 4])
Instead of using the built-in function set ().
2. count objects with Counter.
This sounds obvious, but it is often forgotten. For most programmers, counting one thing is a very common task, and in most cases it is not very challenging-there are several ways to do this more easily.
The collections class library of Python has a built-in dict class subclass, which is dedicated to doing this:
>>> from collections import Counter>>> c = Counter('hello world')>>> cCounter({'l': 3, 'o': 2, ' ': 1, 'e': 1, 'd': 1, 'h': 1, 'r': 1, 'w': 1})>>> c.most_common(2)[('l', 3), ('o', 2)]
3. beautifully printed JSON
JSON is a very good form of data serialization and is widely used by various APIs and web services. Using the built-in json processing in python can make the JSON string readable. However, when a large data is displayed as a long, continuous row, it's hard for people to watch with their eyes.
To make JSON data more friendly, we can use the indent parameter to output beautiful JSON data. This is particularly useful when interactive programming or logging in the console:
>>> import json>>> print(json.dumps(data)) # No indention{"status": "OK", "count": 2, "results": [{"age": 27, "name": "Oz", "lactose_intolerant": true}, {"age": 29, "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 } ]}
Similarly, the built-in pprint module can make the output of other things more beautiful.
4. create a one-time and fast small web service
Sometimes, we need to make some simple, basic RPC interaction between two machines or services. We want to use program B to call A method in program A in A simple way-sometimes on another machine. For internal use only.
I do not encourage the methods described here to be used in non-internal, one-time programming. We can use a protocol called XML-RPC (corresponding to this Python library) to do this.
The following is an example of using the SimpleXMLRPCServer module to create a fast small file read server:
from SimpleXMLRPCServer import SimpleXMLRPCServerdef 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:
import xmlrpclibproxy = xmlrpclib.ServerProxy('http://localhost:8000/')proxy.file_reader('/tmp/secret.txt')
In this way, we get a remote file reading tool without external dependencies and only a few lines of code (of course, there are no security measures, so we can only do this at home ).
5. the magical open-source community of Python
I have mentioned several things in the Python standard library. if you have installed Python, you can use it like this. For many other types of tasks, a large number of third-party libraries maintained by the community are available for you.
The following list is a required condition for a user-friendly and robust open-source library:
Good open-source libraries must...
Include a clear license statement that applies to your use cases.
Development and maintenance work is very active (or, you can participate in development and maintenance .)
It can be easily installed or repeatedly deployed using pip.
There is a test suite with sufficient test coverage.
If you find a good library that meets your requirements, don't be embarrassed-you are welcome to donate code and help for most open-source projects-even if you are not a Python expert.
Original article: Improving Your Python Productivity
The above is a detailed introduction to Python's efficient programming skills. For more information, see other related articles in the first PHP community!