Python comprehension: list comprehension, dictionary comprehension, set comprehension, filter, map, reduce.

list comprehension

  • Example: Divide by 3 numbers 0-100
  • nums=[];
    num=[];
    for i in range(100):
        if i%2==0:
            nums.append(i);
        else:
            num.append(i);
    print(nums);
    print(num);
    
    n=[i for i in range(100) if i%3==0]
    print(n);
  • Call functions
  • def squared(x):
        return x*2;
    wq=[];
    q=[];
    for x in range(30):
        if x%3==0:
            wq.append(squared(x));
    
    q=[squared(y) for y in range(30) if y%3==0]
    print(wq);
    print(q);
  • Use () to generate generators
  • Change the [ ] of the list comprehension to ( ) to get the generator. --yeild
  • def squared(x):
         return x*2;
    q=(squared(y) for y in range(30) if y%3==0);
    print(type(q));
    print(q);

dictionary comprehension

  • The usage of dictionary comprehension and list comprehension is similar, except that the square brackets are changed to curly brackets
  • Example: Quickly replace key and value
  • mcase={'a':10,'b':34};
    for k,v in mcase.items(): #items can be replaced with keys and values, traversing keys and values ​​respectively
        print (k, v);
    
    mk={v:k for k,v in mcase.items()}
    print(mk);

set comprehension

  • They are also similar to list comprehensions. The only difference is that it uses curly braces {}
  • strings=['a','is','with','if','file','exception'];
    l={len(s) for s in strings};
    print(l);

practise:

  • 0-9 to the power of 2
  • l=[i*i for i in range(10)];
    print(l);
  • Convert word length greater than 3 to uppercase output
  • names = ['bob','tom','alice','jerry','wendy','smith']
    a=[name.upper() for name in names if len(name)>3]
    print(a);
  • Find (x, y) where x is an even number between 0-5 and y is a list of tuples consisting of odd numbers between 0-5
  • b=[(x,y) for x in range(6)if x%2==0 for y in range(6)if y%2==1];
    print (b);
  • Find the list of 3,6,9 in m
  • m = [[1,2,3],[4,5,6],[7,8,9]]
    c=[row[2] for row in m];
    print(c);
  • Find the list of slashes 1,5,9 in m
  • m = [[1,2,3],[4,5,6],[7,8,9]];
    d=[m[i][i] for i in range(len(m))];
    print(d);
  • Find the product of the matrix and elements in m, n
  • m = [[1,2,3],[4,5,6],[7,8,9]];
    n = [[2,2,2],[3,3,3],[4,4,4]]
    e=[m[i][j]*n[i][j]for i in range(len(m)) for j in range(len(m[i]))];
    print (s);
  • Combines the elements of two lists if they are not equal
  • m = [[1,2,3],[4,5,6],[7,8,9]];
    n = [[2,2,2],[4,4,4],[7,7,7]];
    L=[(m[i][j],n[i][j]) for i in range(3) for j in range(3)if m[i][j]!=n[i][j] ];
    print(L);

filter:

  • The filter() function includes two parameters, function and list. Whether the function returns true according to the function parameter
  • to filter the items in the list parameter and finally return a new list
  • The function is to perform a filtering operation on the specified sequence
  • foo = [2, 18, 9, 22, 17, 24, 8, 12, 27];
    print(list(filter(lambda x:x%3==0,foo)));

map:

  • The map function will map the specified sequence according to the provided function.
  • The function is to call the function function for each element in the parameter sequence, and return a list containing the return value of each function function.
  • foo = [2, 18, 9, 22, 17, 24, 8, 12, 27];
    print(list(map(lambda x: x * 2 + 10, foo)));

reduce:

  • The reduce() function accumulates the elements in the parameter sequence.
  • import functools,_functools
    foo = [1,2,3,4,5];
    print(functools.reduce(lambda x,y:x+y,foo));#The calculation process is 1+2+3+4+5=15

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325448517&siteId=291194637