I taught you how to put into practice Python developers no longer talk about grammar

I taught you how to put into practice Python developers no longer talk about grammar

 

 

1. Derivation dictionary (Dictionary comprehensions) and a set of derived (Set comprehensions)

Most Python programmers know and used to derive a list (list comprehensions). If you are not very familiar with the list comprehensions concept - one is a shorter and concise method of creating a list of list comprehension.

>>> 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 2.7 Python ) onwards, we can use the same syntax to create a collection 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_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 have a some_listbasis to create a duplicate set of elements has not, and the collection contains only even numbers. In the example of dictionary tables, we have created a duplicate key is not an integer between 1 and 10, value is a Boolean to indicate whether the key is even.

Here is another thing to note is the literal representation of a collection method. We can simply create a collection in this way:

>>> my_set = {1, 2, 1, 2, 3, 4}

>>> my_set
set([1, 2, 3, 4])

  

Without the use of built-in functions set().

2. Use Counter counts the count target.

This sounds obvious, but often forgotten. For most programmers, a number of things is a very common task, and in most cases is not very challenging thing - There are several ways this can be done simpler task.

Python's collections class library has built a dictsubclass of the class, it is designed to do such a thing:

>>> 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. JSON pretty print out

JSON is a very good form of the data sequence, are used today a large number of various API and web service. Python using the built-in jsonhandle, can make JSON string has a certain readability, but the face of large-scale data, it appears to be a very long, continuous row, the human eye is difficult to watch.

In order to make the performance more friendly JSON data, we can use the indentparameters to output nice JSON. When the console log or doing interactive programming, which is particularly useful:

>>> 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
    }
  ]

}

  

Again, using the built-in pprint module also allows any other thing more beautiful printouts.

4. Create a one-time, fast small web service

Sometimes we do need to interact with some of the simple, very basic RPC like between two machines or services. A program we want to call a method in the B program in a simple way - sometimes on another machine. Internal use only.

I do not encourage the approach presented here is used in non-internal, one-off programming. We can use a technique called XML-RPC protocol (this corresponds to a Python library ), to do this kind of thing.

Here's a SimpleXMLRPCServerfile server to read examples of modules to build a fast small:

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:

import xmlrpclib
proxy = xmlrpclib.ServerProxy('http://localhost:8000/') proxy.file_reader('/tmp/secret.txt')

We thus get a remote file reading tool, there is no external dependencies, only a few of code (of course, without any safety measures, it can only do this at home).

Guess you like

Origin www.cnblogs.com/itman123/p/11614029.html