python - lambda expressions and built-in functions

1 lambda expressions (anonymous function)

For representing simple function

lambda expressions, in order to solve simple function of cases:

def func(a1,a2):       =====> func = lambda a1,a2:a1+a2  # 函数直接得到返回值,这里隐藏了return
    return a1+a2       简化
# 三元运算,为了解决简单的if else的情况,如:
if 1 == 1:
    a = 123
else:
    a = 456

a =  123  if 1 == 1 else 456

# lambda表达式,为了解决简单函数的情况,如:
def func(a1,a2):
    return a1 + 100 

func = lambda a1,a2: a1+100
func1 = lambda : 100 

func2 = lambda x1: x1 * 10

func3 = lambda *args,**kwargs: len(args) + len(kwargs)

DATA = 100
func4 = lambda a1: a1 + DATA
v = func4(1)
print(v)

DATA = 100
def func():
    DATA = 1000
    func4 = lambda a1: a1 + DATA
    v = func4(1)
    print(v)
func()

func5 = lambda n1,n2: n1 if n1 > n2 else n2
v = func5(1111,2)
print(v)

lambda expression can only be represented by a line function can only be used as a variable parameter.

Exercises

# 练习题1
USER_LIST = []
def func0(x):
    v = USER_LIST.append(x)
    return v 

result = func0('alex')
print(result)


# 练习题2

def func0(x):
    v = x.strip()
    return v 

result = func0(' alex ')
print(result)

############## 总结:列表所有方法基本上都是返回None;字符串的所有方法基本上都是返回新值 #################
# 练习题3
USER_LIST = []
func1 = lambda x: USER_LIST.append(x)

v1 = func1('alex')
print(v1)
print(USER_LIST)

# 练习题4
func1 = lambda x: x.split('l')

v1 = func1('alex')
print(v1)

# 练习题5
func_list = [lambda x:x.strip(), lambda y:y+199,lambda x,y:x+y]

v1 = func_list[0]('alex ')
print(v1)

v2 = func_list[1](100)
print(v2)

v3 = func_list[2](1,2)
print(v3)

to sum up:

The method returns a list of all basically None, all methods basically strings return the new value.

2 built-in functions

Functions are divided into: built-in functions and custom functions

Currently python's built-in functions divided into several categories:

  • 1. cast

    bool() / int() / str() / list() / dict() /tuple() / set()

  • 2. Input Output

    print() / input()

  • 3. Other

    len() / open() / id() / range() / type()

  • 4. mathematical correlation

      1. abs () absolute value

        v = abs(-1)
        print(v)   # 1
      2. float () is converted into float (decimal)

        v = 55
        v1 = float(v)
        print(v1)    # 55.0
      3. max () to find the maximum value

        v = [1,2,33,5,9]
        result = max(v)
        print(result)   # 33
      4. min () to find the minimum

        v = [1,2,311,11,8]
        v2 = min(v)
        print(v2)  # 1
      5. sum () sums

        v = [1,2,311,11,9]
        v1 = sum(v)
        print(v1)  # 334
      6. divmod () dividing the two quotient and remainder

        a,b = divmod(1001,5)
        print(a,b)   # 200  1

        Added: String Format: 'You Shaoqi -% s'% (i,) ------> rear% (i,) if only one of the variables in brackets, can be written as:' You Shaoqi -% s '% i

        # 练习题  请通过分页对数据进行展示
        """
        要求:
            每页显示10条数据
            让用户输入要查看的页面:页码
        """
        
        USER_LIST = []
        for i in range(1,836):
            temp = {'name':'你少妻-%s' %i,'email':'123%[email protected]' %i }
            USER_LIST.append(temp)
        
        # 数据总条数
        total_count = len(USER_LIST)
        
        # 每页显示10条
        per_page_count= 10
        
        # 总页码数
        max_page_num,a = divmod(total_count,per_page_count)
        if a>0:
            max_page_num += 1
        
        while True:
            pager = int(input('要查看第几页:'))
            if pager < 1 or pager > max_page_num:
                print('页码不合法,必须是 1 ~ %s' %max_page_num )
            else:
                """
                # 第1页:USER_LIST[0:10] -> 0123456789
                # 第2页:USER_LIST[10:20]
                # 第3页:USER_LIST[20:30]
                ...
                """
                start = (pager-1) * per_page_count
                end = pager * per_page_count
                data = USER_LIST[start:end]
                for item in data:
                    print(item)
      • 7.pow

        pow (x, y) represents the y-th power of x

        v = pow(2,3)
        print(v)   # 8
      • 8.round reserved several decimal places after the decimal point, but also rounding.

        V = round(1.127,1/2)
        print(v)   # 1.1 / 1.13
  • 5. decimal conversions

    • bin () to convert decimal to binary

      num = 13
      v1 = bin(num)
      print(v1)  # 0b1101
    • oct () to convert from decimal to octal

      num = 8
      v1 = oct(num)
      print(v1)  # 0o10
    • int () converts the hexadecimal to decimal other

      # 二进制转化成十进制
      v1 = '0b1101'
      result = int(v1,base=2)
      print(result)  # 13
      
      # 八进制转化成十进制
      v1 = '0o1101'
      result = int(v1,base=8)
      print(result)
      
      # 十六进制转化成十进制
      v1 = '0x1101'
      result = int(v1,base=16)
      print(result)
    • hex () to convert decimal to hexadecimal

      num = 16
      v1 = hex(num)
      print(v1)  # 0x10

      Exercises

      # 1字节等于8位
      # IP: 192.168.12.79  ->  001010010 . 001010010 . 001010010 . 001010010
      
      # 1. 请将 ip = "192.168.12.79" 中的每个十进制数转换成二进制并通过,连接起来生成一个新的字符串。
      ip = "192.168.12.79"
      ip_list = ip.split('.') # ['192','168','12','79']
      result = []
      for item in ip_list:
          result.append(bin(int(item)))
      print(','.join(result))
      
      
      # 2. 请将 ip = "192.168.12.79" 中的每个十进制数转换成二进制: 
      #          0010100100001010010001010010001010010 -> 十进制的值。
      
      # 3232238671
      
      ip = "192.168.12.79"
      ip1 = ip.split('.')
      lis = []
      for i in ip1: 
          lis.append(bin(int(i)))
      # val = ','.join(lis)
      # b = val.replace('0b', '')
      # b1 = b.split(',')
      b1 = ','.join(lis).replace('0b', '').split(',')
      e = []
      #f or c in b1:
      for c in ','.join(lis).replace('0b', '').split(','):
          if len(c) < 8:
              val = 8 - len(c)
              d = list(c)
              d.insert(0,'0' * val)
              d1 = ''.join(d)
              e.append(d1)
          else:
              e.append(c)
      f = ''.join(e)
      f1 = int(f,base = 2 )
      print(f1)
  • 6. coding related

    • chr into corresponding decimal number string encoded in Unicode

      v = chr(65)
      print(v)   # A
    • ord to find the corresponding decimal encoding of the character in the Unicode

      v = ord('中')
      print(v)    # 20013
    • application:

      import random
      
      v = random.randint(65,90)
      print(v)   # 随机获得65~90之间的数字
      
      
      import random
      
      data = []
      for i in range(6)
          v = random.randint(65,90)
          data.append(chr(v))
      print(''.join(data))   # 6位随机字符串验证码
      
      
      import random
      
      def get_random_code(length=6):
          data = []
          for i in range(length):
              v = random.randint(65,90)
              data.append(chr(v))
      
          return  ''.join(data)
      
      
      code = get_random_code()
      print(code)    # 6位随机字符串验证码
      import random # 导入一个模块 
      
      v = random.randint(起始,终止) # 得到一个随机数
  • 7. High point of the built-in functions

    • map cycle each element (the second parameter), and then let each element performs the function (first parameter) to save the results of each function performed to the new list, and return.

      V1 = [11,22,33,44]
      # map(x,v1) 第一个参数必须是函数,第二个参数必须是可迭代类型(可以被for循环的)
      def func(arg):
          print(arg)
      # map(func,v1)    # 执行后并不打印arg,这是py3的一个特性,py3现在还不执行以后会执行
      result = map(func,v1)  # 然后将函数的返回值添加到一个[]中
      
      # print(result)  py2会直接返回列表
      # print(result)  py3不会,会得到一个对象/东西,想返回列表的话需要强制转换成列表
      
      print(list(ruselt))  # result得到的是一个对象<map.objecta……>,需要list()才能打印列表
      v1 = [11,22,33,44]
      result = map(lambda x:x+100,v1)
      print(list(result)) # 特殊
    • filter

      result = filter (function parameters)

      v1 = [11,22,33,'asd',44,'xf']
      
      def func(x):
          if type(x) == int:
              return True
          return False
      result = filter(func,v1) # [11,]
      print(list(result))
      
      
      result = filter(lambda x: True if type(x) == int else False ,v1)
      print(list(result))
      
      result = filter(lambda x: type(x) == int ,v1)
      print(list(result))
    • reduce the cumulative get a result

      reduce py3 is not in the kind of built-in functions, but the built-in function of py2 contains.

      import functools
      v1 = ['wo','hao','e']
      
      def func(x,y):
          return x+y
      result = functools.reduce(func,v1) 
      print(result)
      
      result = functools.reduce(lambda x,y:x+y,v1)
      print(result)
  • 8. A related class

      1. type, type of view

        class Foo:
            pass
        
        obj = Foo()
        
        if type(obj) == Foo:
            print('obj是Foo类的对象')
      2. issubclass

        Determining a class is not a subclass of another class, or a base class.

        issubclass (Class 1, Class 2) are 1-> subclass name, category 2-> base class name

        class Base:
            pass
        
        class Base1(Base):
            pass
        
        class Foo(Base1):
            pass
        
        class Bar:
            pass
        
        print(issubclass(Bar,Base))
        print(issubclass(Foo,Base))
      3. isinstance

        Determining whether an object is an instance of a class or a base class (object)

        class Base(object):
            pass
        
        class Foo(Base):
            pass
        
        obj = Foo()
        
        print(isinstance(obj,Foo))  # 判断obj是否是Foo类或其基类的实例(对象)
        print(isinstance(obj,Base)) # 判断obj是否是Foo类或其基类的实例(对象)
      4. super

        class Base(object):
            def func(self):
                print('base.func')
                return 123
        
        
        class Foo(Base):
            def func(self):
                v1 = super().func()
                print('foo.func',v1)
        
        obj = Foo()
        obj.func()
        # super().func() 去父类中找func方法并执行
        class Bar(object):
            def func(self):
                print('bar.func')
                return 123
        
        class Base(Bar):
            pass
        
        class Foo(Base):
            def func(self):
                v1 = super().func()
                print('foo.func',v1)
        
        obj = Foo()
        obj.func()
        # super().func() 根据类的继承关系,按照顺序挨个找func方法并执行(找到第一个就不在找了)
        class Base(object): # Base -> object
            def func(self):
                super().func()
                print('base.func')
        
        class Bar(object):
            def func(self):
                print('bar.func')
        
        class Foo(Base,Bar): # Foo -> Base -> Bar
            pass
        
        obj = Foo()
        obj.func()
        
        # 多继承
        # super().func() 根据self对象所属类的继承关系,按照顺序挨个找func方法并执行(找到第一个就不在找了)

        super (). To find

        super (). func () based on inheritance self object belongs to the class of (from left to right to find), one by one in order to find methods and implement func (find not find the first one)

        super follow mro order to find on a class

        supper (). func () instead of looking for the father, but according mro order to find the next class corresponding to their own

Guess you like

Origin www.cnblogs.com/yangjie0906/p/11215765.html