Python finishing

1. json.dumps和json.loads

  json module provides a very simple way to encode and decode data JSON. Wherein the two main functions are json.dumps () and json.loads (), than the other sequences of such libraries pickle interface much less.

 1.1 The following demonstrates how to convert a Python data structures to JSON:

  
import json

data = {
    'name' : 'ACME',
    'shares' : 100,
    'price' : 542.23
}

json_str = json.dumps(data)

  

 1.2 The following demonstrates how a JSON-encoded string back to a data structure Python:

data = json.loads(json_str)
 

   1.3 If you want to deal with is the file instead of a string, you can use json.dump () and json.load () to encode and decode JSON data. E.g:

# Write json file 
with Open ( ' the data.json ' , ' W ' ) AS F:
    json.dump(data, f) 

# Read json file 
with Open ( ' the data.json ' , ' R & lt ' ) AS F:
    data = json.load(f)

 

2. iterator

  1.1 iterables

    We already know, for loop can act directly on the data types are the following:
      A class is a collection of data types, such as a list, tuple, dict, set, str like;
      One is the generator, comprising a generator and a band of yield generator function.
      These can act directly on an object referred to as a for loop iterables: Iterable.
    Can use the isinstance () determines whether an object is an object Iterable:

  1.2 iterator

    The generator not only can act on a for loop, you can be next () function continues to call and returns the next value, until the last error thrown StopIteration said it could not continue to return the next value.
    May be next () function call and return to the next target value continuously referred iterator: Iterator.
    Can use the isinstance () determines whether an object is an object Iterator:
      Generator Iterator objects are, but the list, dict, str though Iterable, not the Iterator.
      The list, dict, str becomes like Iterable Iterator may be used ITER () function
 

3. Closure

  Function returns inside the local variables defined reference args, so that, when a function returns a function, its local variables inside a function reference is also new,
def count():
    fs = [] 
    for i in range(1, 4): 
        def f(): 
            return i*i 
    fs.append(f) 
return fs
 
f1, f2, f3 = count()

 

4. The operation of the dictionary

Students' math scores are stored in a dictionary, which screened score more than 80 points classmates
 from Random Import randint
d = {x:randint(50,100) for x in range(1,21)}
 
res = {k:v for k, v in d.items() if v > 80}
 
filter function
data = {-1, -5,-8,0, 2, 6, 8, 89}
res = list(filter(lambda x: x>=0, data)
print(res)
 
List derived using the formula: RES = {I for I in Data IF I> 0}

 

Guess you like

Origin www.cnblogs.com/ladder/p/11932937.html