Python (4)

Source: Internet
Author: User
Tags define function square root variable scope

Practice Code:

(1) https://gitee.com/pythonbigdata/pythonTest01/blob/master/Test/Def.py (use of variable functions, and three function big data needed in big data)

(2) https://gitee.com/pythonbigdata/pythonTest01/blob/master/Test/Class.py (use and Invocation of class properties)

#全局变量放在函数体外, local variables are placed inside the function body, and if the global variables keyword is used within the function body#可变类型的不用写global, for global variables, the need for immutable types Global keyword#当返回值为多个是, automatically assemble as a tuple, or use multiple variables to accept#使用reduce需要导入模块 from functools import reduce#map的两种使用方式#Python中方法也是一个对象# You can use TT directly as an object, TT (x) is called method

Functions are well-organized, reusable pieces of code that are used to implement single, or associated functions
2. Syntax:
def function name (parameter list):
function body
Return XXX
You can return multiple values, return multiple values to form a tuple, return a value plus a pair of brackets, and return a list
Functions are divided into definitions and call functions
Exercise: Define a function that implements the addition, subtraction, multiplication, and addition of two numbers
3. Can change (mutable) and non-change (immutable) objects
In Python, strings, tuples, and numbers are objects that cannot be changed, and List,dict are objects that can be modified.
Immutable type: Variable assignment a=5 and then assign value a=10, here is actually reborn into an int value object 10, then a point to it, and 5 is discarded, not change the value of a, the equivalent of a new student into a.
Variable type: variable assignment la=[1,2,3,4] After assigning a value la[2]=5 is to change the value of the third element of List LA, itself LA is not moving, but its internal part of the value has been modified.
Parameter passing of the Python function:
Immutable types: Values such as C + + are passed, such as integers, strings, and tuples. such as fun (a), passing only a value, does not affect the A object itself. For example, in Fun (a) to modify the value of a, just modify another copy of the object, does not affect the a itself.
mutable types: References such as C + + are passed, such as lists, dictionaries. such as Fun (LA), is the real transfer of LA, the modified fun outside of LA will also be affected
4. The following are the formal parameter types that can be used when calling a function:
Required Parameters
Keyword parameter: The keyword parameter allows you to pass in 0 or any parameter with parameter names that are automatically assembled inside the function as a dict dictionary
Example: # keyword parameter: **kw
def person (name,age,**kw):
Print (' name: ', Name, ' Age: ', age, ' other: ', kw)
Person (' Frank ', ' 37 ')
Person (' Frank ', ' PNs ', city= ' Shanghai ')
Person (' Frank ', ' PNs ', gender= ' M ', job= ' Engineer ')
Can also be written in the following simple form:
Extra = {' City ': ' Beijing ', ' job ': ' Engineer '}
Person (' Jack ', **extra)
Note that the dict obtained by KW is a copy of the extra, and the changes to KW do not affect the extra outside the function.
Default parameters: (default parameter) the default parameter must be written in the following, you can not specify the parameter name, but the order is guaranteed, otherwise you want to specify the parameter name
#可写函数说明
def printinfo (name, age = 35):
"Print any incoming string"
Print ("Name:", name);
Print ("Age:", ages);
Return

#调用printinfo函数
Printinfo (age=50, name= "Runoob");
Print ("------------------------")
Printinfo (name= "Runoob");
Indefinite length parameter (variable parameter):
Variable parameters allow you to pass in 0 or any of the parameters, which are automatically assembled as a tuple when the function is called

def calc (numbers):
sum = 0
For N in numbers:
sum = SUM + N * n
return sum
But when called, a list or tuple needs to be assembled first:

>>> Calc ([1, 2, 3])
14
>>> Calc ((1, 3, 5, 7))
84
If you take advantage of mutable parameters, the way you call a function can be simplified to this:

>>> Calc (1, 2, 3)
14
>>> Calc (1, 3, 5, 7)
84
So, let's change the parameter of the function to a variable parameter:

Def calc (*numbers):
sum = 0
For N in numbers:
sum = SUM + N * n
return sum
When you define a mutable parameter and define a list or tuple parameter, you add an * number just before the parameter. Inside the function, the parameter numbers receives a tuple, so the function code is completely unchanged. However, when you call the function, you can pass in any parameter, including 0 parameters:

>>> Calc (1, 2)
5
>>> Calc ()
0
What if you have a list or a tuple and you want to invoke a mutable parameter? You can do this:

>>> nums = [1, 2, 3]
>>> Calc (nums[0], nums[1], nums[2])
14
This kind of writing is of course feasible, the problem is too cumbersome, so python allows you to precede the list or tuple with an * number, the list or tuple of the elements into a variable parameter to pass in:

>>> nums = [1, 2, 3]
>>> Calc (*nums)
14
*nums indicates that all elements of the list are nums as mutable parameters. This writing is quite useful and common.
Parameter combinations
Define functions in Python, which can be combined using required parameters, default parameters, variable parameters, keyword arguments, and named keyword parameters, except that mutable parameters cannot be mixed with named keyword parameters. Note, however, that the order of the parameter definitions must be: required, default, variable/named keyword, and keyword parameters.

For example, define a function that contains several of the above parameters:

Def f1 (A, B, c=0, *args, **kw):
Print (' A = ', A, ' B = ', B, ' C = ', C, ' args = ', args, ' kw = ', kw)

def F2 (A, B, c=0, *, D, **kw):
Print (' A = ', A, ' B = ', B, ' C = ', C, ' d = ', D, ' kw = ', kw)
The most amazing thing is that through a tuple and dict, you can also call the above function:

>>> args = (1, 2, 3, 4)
>>> kw = {' d ':, ' x ': ' # '}
>>> F1 (*args, **kw)
A = 1 b = 2 c = 3 args = () kw = {' d ':, ' x ': ' # '}
>>> args = (1, 2, 3)
>>> kw = {' d ': ", ' X ': ' # '}
>>> F2 (*args, **kw)
A = 1 b = 2 c = 3 d = x kw = {' × ': ' # '}
So, for any function, it can be called by the form of a func (*args, **kw), regardless of how its arguments are defined.
Return xxx,xxx,xxx
will return a tuple
Returning several values when calling a function can also be received with several variables
def f3 (A,b,c=0,d=none):
Print (C,D)
F3 (1,2,d=5) #命名参数
Def f4 (A, B):
a,b=11,12
Return a,b# automatically form a tuple when multiple values are returned
C,D=F4 (#也可以使用多个变量接收)


Summary
Python's functions have a very flexible parameter pattern, which allows for simple invocation and very complex parameters to be passed.
Default parameters must be used immutable objects, if it is a mutable object, the program will run with a logic error!
Be aware of the syntax for defining mutable parameters and keyword parameters:
*args is a variable parameter, and args receives a tuple;
**KW is the keyword parameter, and kw receives a dict.
Variable scope:
Global variables are scoped differently from local variables
Different life cycle
Global variables:
g_a=10
Def test2 ():
Global g_a# tells the program that this is a globally variable
G_a=20
Print (G_A)
def test3 ():
Print (G_A)
Test2 ()
Test3 ()
When a global variable has the same name as a local variable, the local variable takes precedence
Local variables
When lists and dictionaries are global variables, do not add global
Anonymous functions:
Python uses lambda to create anonymous functions
Syntax: lambda [arg1 [, Arg2,..... argn]]:expression
# Writable Function Description
sum = lambda arg1, arg2:arg1 + arg2;
SUM (+)
def XXX (ARG1,ARG2):
Return ARG1+ARG2
Sum=xxx (10,20)
# Call the SUM function
Print "added value is:", SUM (10, 20)
Print "added value is:", SUM (20, 20)

def add (A,b,fun):
Print (fun (b))
Add (11,22,lambda arg1, ARG2:ARG1-ARG2)

# define functions (normal way)
def func (ARG):
return arg + 1

# Execute function
result = Func (123)

# ###################### Lambda ######################
# define function (lambda expression)
My_lambda = lambda Arg:arg + 1
# Execute function
result = MY_LAMBDA (123)
Three important big data functions to use:

Fliter filter conditions are met before output
>>> foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
>>> Print filter (lambda x:x% 3 = = 0, foo)
[18, 9, 24, 12, 27]

#map的两种使用方式#Python中方法也是一个对象# You can use TT directly as an object, TT (x) is called method

>>> Print Map (Lambda x:x * 2 + ten, foo)
[14, 46, 28, 54, 44, 58, 26, 34, 64]

#使用reduce做数字统计
>>> print reduce (lambda x, y:x + y, foo)

139

Three important big data functions to use:
>>> foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
>>> Print filter (lambda x:x% 3 = = 0, foo)
[18, 9, 24, 12, 27]
>>> Print Map (Lambda x:x * 2 + ten, foo)
[14, 46, 28, 54, 44, 58, 26, 34, 64]
>>> print reduce (lambda x, y:x + y, foo)
139
Python map ()
The map () function receives two parameters, one is a function, the other is a sequence, and map passes the incoming function to each element of the sequence sequentially, returning the result as a new list.
For example, we have a function f (x) =x%2, to function in a list [1, 2, 3, 4, 5, 6, 7, 8, 9], you can use map () to achieve
#使用lambda函数
Case 1:
Print map (lambda x:x% 2, range (7))
[0, 1, 0, 1, 0, 1, 0]
Case 2:
Li = [11, 22, 33]
New_list = map (lambda a:a + li)
Python filter (): Filters the elements in a sequence and eventually gets a sequence that matches the condition
Li = [11, 22, 33]
New_list = filter (lambda arg:arg > P, li)
For example, to delete an even number from a list [1, 4, 6, 7, 9, 12, 17] and keep an odd number, first, write a function that judges the odd number:
def is_odd (x):
return x% 2 = = 1
Then, filter out the even number using filter ():
>>>filter (Is_odd, [1, 4, 6, 7, 9, 12, 17])
Results:
[1, 7, 9, 17]
With filter (), you can accomplish many useful functions, such as deleting None or an empty string:
def is_not_empty (s):
return s and Len (S.strip ()) > 0
>>>filter (Is_not_empty, [' Test ', None, ' ', ' str ', ' ', ' END '])
Results:
[' Test ', ' str ', ' END ']
Note: S.strip (RM) Deletes the characters of the RM sequence at the beginning and end of the S string.
When RM is empty, the default is to remove the white space character (including ' \ n ', ' \ R ', ' \ t ', '), as follows:


>>> a = ' 123 '
>>> A.strip ()
' 123 '


>>> a = ' \t\t123\r\n '
>>> A.strip ()
' 123 '


Practice:
Filter () to 1~100 that the square root is an integer number, i.e. the result should be:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Method:
Import Math
def IS_SQR (x):
return math.sqrt (x)% 1 = = 0
Print filter (IS_SQR, Range (1, 101))
Results:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Python reduce (): Cumulative operation for all elements within a sequence
Li = [11, 22, 33]
result = reduce (lambda arg1, Arg2:arg1 + arg2, Li)
Reduce in Python
The reduce built-in function in Python is a two-dollar operation function that uses all the data from a collection of data (linked lists, tuples, and so on) to do the following: The function func (which must be a two-dollar operation function) passed to reduce will first operate on the 1th and 2 data in the set. The resulting result is then calculated with the third data using the Func () function, and finally a result is obtained.
Such as:
def myadd (x, y):
Return X+y
Sum=reduce (Myadd, (1,2,3,4,5,6,7))
Print sum
The result of #结果就是输出1 +2+3+4+5+6+7 is 28.
Of course, you can also use the lambda method, which is simpler:
Sum=reduce (Lambda X,y:x+y, (1,2,3,4,5,6,7))
Print sum
The reduce () function is also a high-order function built into Python. The reduce () function receives a parameter similar to map (), a function f, a list, but behaves differently from map (), and reduce () the incoming function f must receive two parameters, and reduce () calls function f repeatedly on each element of the list and returns the final result value.


For example, write an F function that receives x and Y, and returns the and of X and Y:


def f (x, Y):
return x + y
When you call reduce (f, [1, 3, 5, 7, 9]), the Reduce function calculates the following:


First two elements are computed: F (1, 3), and the result is 4;
Then the result and the 3rd element are calculated: F (4, 5), the result is 9;
Then the result and the 4th element are calculated: F (9, 7), the result is 16;
Then the result and the 5th element are calculated: F (16, 9), the result is 25;
Since there are no more elements, the calculation ends and the result 25 is returned.
The above calculation is actually a summation of all the elements of the list. Although Python has built-in sum function sum (), it is simple to sum with reduce ().


Reduce () can also receive a 3rd optional parameter as the initial value of the calculation. If you set the initial value to 100, the calculation:
Reduce (f, [1, 3, 5, 7, 9], 100)
The result will change to 125 because the first round calculation is:


Calculates the initial value and the first element: F (100, 1), and the result is 101.


Practice:
Python has built-in sum function sum (), but there is no quadrature function, use reduce () to calculate the product:
Input: [2, 4, 5, 7, 12]
Output: Results of 2*4*5*7*12


Method:
def prod (x, y):
Return X*y
Print reduce (prod, [2, 4, 5, 7, 12])
Results:
>>>3360
Custom sort functions in Python:
The python built-in sorted () function can sort the list:


>>>sorted ([36, 5, 12, 9, 21])
[5, 9, 12, 21, 36]
But sorted () is also a high-order function, which can receive a comparison function to implement a custom sort, the definition of the comparison function is to pass in two elements to be compared x, y, if X should be in front of y, return-1, if X should be ranked after Y, return 1. returns 0 if x and y are equal.




Sorted () can also sort strings, and strings are compared by default in ASCII size:


>>> sorted ([' Bob ', ' about ', ' Zoo ', ' credits '])
[' Credits ', ' Zoo ', ' about ', ' Bob ']
The ' Zoo ' was ranked before ' about ' because the ' Z ' ASCII code was smaller than ' a '.
. Sort () Sorting method
Shus.sort () sort the original list, change the order of the original list, no return value
Print (SHUs) is the changed list
Sorted () Sort function
Sorting does not affect the original data, resulting in new sorting data
Print (sorted (SHUs)) sorted results
Print (SHUs) or the original result


Practice:
When sorting strings, it is sometimes more customary to ignore the case sort. Use the sorted () higher-order function to implement an algorithm that ignores case ordering.


Input: [' Bob ', ' about ', ' Zoo ', ' credits ']


>>> a = [' Bob ', ' about ', ' Zoo ', ' credits ']
>>> Print (sorted (A, key=str.lower))


Results:
[' About ', ' Bob ', ' credits ', ' Zoo ']

Python (4)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.