pythonreduce() function, sorted() function, reversed_cmp function, classes and objects

reduce(): Accumulates all elements in the sequence

  • import _functools
    li = (1,2,3,4,5,6,7);
    def add(a,b):
        return a+b;
    total=_functools.reduce(add,li);
    print(total);
  • reduce() can also receive a third optional parameter as the initial value of the calculation
  • import _functools
    li = (1,2,3,4,5,6,7);
    def add(a,b):
        return a+b;
    total=_functools.reduce(add,li,100);#The initial value is 100
    print(total);

sorted() sorts the list:

  • ol=[1,5,3,7,9,33,45,10];
    ul=sorted(ol);
    the prince);
  • ol=[True,False];
    ul=sorted(ol);
    the prince);

reversed_cmp function:

  • ol=[1,5,3,7,9,33,45,10];
    ul=sorted(ol,reverse=True);#The default positive order is False
    the prince);
  • ol=[('Bob',74),('Adam',92),('Bart',66),('List',88),('aisa',88)];
    print(ol);
    ol=sorted(ol,key=lambda s:str(s[0]).lower(),reverse=False);
    print(ol);

Small exercise:

  • Write the address book management system by the function method
  • # usr/bin/python
    # -*-coding:utf-8-*-
    flag = True;
    names = ['ok', 'ko'];
    phones = ['232323232', '12312332'];
    
    def Menu():
        global flag
        while flag:
            print("\n\n========Address Book Management System=======")
            print("1. Add name and mobile phone")
            print("2. Delete name")
            print("3. Modify the phone")
            print("4. Query all users")
            print("5. Find the phone number according to the name")
            print("6. Exit")
            print("============================")
            i = int(input("Please choose: "));
            while True:
                if i in range(1, 7):
                    break;
                else:
                    i = int(input("Incorrect input, please re-enter!"))
            if i == 1:
                addUser();
            elif i == 2:
                delUser ();
            elif i == 3:
                updatePhone();
            elif i == 4:
                showList ();
            elif i == 5:
                getPhoneByName()
            elif i == 6:
                flag = False;
    def addUser():
        name=input('Please enter your name:')
        if checkUser(name)!=-1:
            print("Name already exists!")
        else:
            names.append(name);
            phones.append(input('Please enter the phone number: '));
    
    def delUser():
        name = input("Please enter your name: ");
        index=checkUser(name)
        if index!=-1:
            names.pop(index);
            phones.pop(index);
            print("Deleted successfully!")
        else:
            print("Name does not exist!")
    
    def updatePhone():
        phone = input("Please enter the phone number: ");
        index=checkPhone(phone);
        if index!=-1:
            new_phone = input("Please enter a new phone number: ");
            phones[index] = new_phone
            print("Modified successfully!")
        else:
            print("Phone number does not exist!")
    
    def showList():
        for i in range(len(names)):
            print(names[i], phones[i])
    
    def getPhoneByName():
        name = input("Please enter your name: ");
        index=checkUser(name)
        if index!=-1:
            print("Phone number:", phones[index])
        else:
            print("Name does not exist!")
    
    def checkPhone(phone):
        if phone in phones:
            return  phones.index(phone)
        else:
            return -1;
    def checkUser(name):
        '''
        :param name The name to look for:
        :return has: subscript without -1:
        '''
        if name in names:
            return  names.index(name)
        else:
            return -1;
    
    Menu();

classes and objects

  • class Student:# The name of the class cannot use characters other than underscores and cannot start with a number
        pass# is used to ensure proper integrity and semantic integrity
  • Attributes are classified into class attributes and object attributes
  • There are two ways to create object properties:
  • 1. self: the carrier of the object
  • class Student:
        def __init__(self,name,age):
            self.name=name;
            self.age=age;
        def showName (self):
            print("My name is {}".format(self.name));
    zhangsan=Student('Zhang San',30);
    zhangsan.showName()
  • 2. Created by object.property()
  • class Student:
        def showName (self):
            print("My name is {}".format(self.name));
    zhangsan=Student();
    zhangsan.name='Zhangsan';
    zhangsan.showName()
  • class Student:
        def showName (self):
            print("My name is {}".format(self.name));
    zhangsan=Student();
    zhangsan.name='Zhangsan';
    zhangsan.name='ok';#The second value will overwrite the first value
    zhangsan.showName()

Guess you like

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