Python function Advanced

Source: Internet
Author: User

First, function is variable

def say (name):
Print (name)
YBQ = say #可以被赋值给其他变量
YBQ (' amily ') #调用函数

Function Name: Say

function Body: 1–2 line

Return value: The value after return

Memory address of function: When the function body is read into memory, it is referenced by the identifier that is the function name say.
In other words, say points to the location where the function body is stored within memory.

Function name parentheses: For example, say (), function call method, only see this parenthesis, the program will be based on
The function name finds the function body from memory and executes it

function names, function parentheses can be passed as arguments, or return values can be returned, and there are two distinct meanings of parentheses

def say (name): #定义函数
Print (name)

YBQ = say #可以被赋值给其他变量
YBQ (' amily ') #调用函数
Print (say) # printing function memory address
Print (type (say)) #打印函数的类型
Print (ID (say)) #打印函数的id

Output Result:

amily
<function say at 0x0000000000b301e0>
<class ' function ' >
11731424

Second, built-in function: map/filter/sorted

map () The map() function receives two parameters, one is a function, one is an iterative object (iterable), and the map passed function functions sequentially to each element of the sequence and returns the result as a new, iterative object

Filter () and map() similar, filter() also receive a function and a sequence. And the map() difference is that the filter() incoming function acts on each element in turn, and then whether True False the element is persisted or discarded based on the return value.

Example 1:

def func (a): #求偶数
if a%2==0:
return True
Else:
return False
nums = [x for x in range]
all_res = []
res = map (func,nums)
res1 = Filter (func,nums)
Print (res) #循环调用函数, and then put the result of each function processing into a list and return

Print (list (res1))

Output Result:

[True, False, True, False, True, False, True, False, True, False, True]
[0, 2, 4, 6, 8, 10]

Example two: (Lambda anonymous function)

res = filter (lambda x:x > 5, [12, 3, 12, 2, 1, 2, 35])
Res1 = map (lambda x:x > 5, [1, 2, 3, 4, 5, 6])
Print (list (res))
Print (list (res1))
Output Result:

[12, 12, 35]
[False, False, False, False, False, True]

Sorted () #升序排列

Sorted (, reverse = True) #降序排列

Output Result:

Third, processing JSON

The Python JSON module can handle simple data types (string, Unicode, int, float, list, tuple, dict) directly.

The Json.dumps () method returns a Str object that has a conversion process from the original Python type to the JSON type in the encoding process, with the specific conversions as follows

It is important to note that the dictionary type key in the JSON string must be double-quoted "" Json.loads () to parse correctly

1. Convert python data structure to Json Format (encoding) Json.dumps ()

The indent parameter is the indentation meaning, which makes the data storage format more elegant and more readable, which is populated by adding some redundant spaces. However, when decoding (Json.loads ()), the blank padding is removed.

Loads will be removed when the added intent padding space is dumps

Ensure_ascii parameter Display Chinese

Instance:

Import JSON
D = {
' car ': {' color ': ' Red ', ' price ': +, ' count ': 50},
' car1 ': {' color ': ' Red ', ' price ': +, ' count ': 50},
' Car2 ': {' color ': ' Red ', ' price ': +, ' count ': 50},
' Car3 ': {' color ': ' Red ', ' price ': +, ' count ': 50},
' CAR4 ': {' color ': ' Red ', ' price ': +, ' count ': 50},
' Car5 ': {' color ': ' Red ', ' price ': +, ' count ': 50},
}
res = Json.dumps (d,indent=8,ensure_ascii=false) #把list, dictionary converted to json,indent how many indents, Ensure_ascii can display in Chinese
F1 = open (' F1 ', ' W ', encoding= ' utf-8 ')
F1.write (RES)

Output Result:

2. Convert JSON format to PYTHON data structure (decode) json.loads ()

Instance:

F1 = open (' F1 ', encoding= ' utf-8 ')
res = F1.read ()
Dict_res = json.loads (res) #把json串变成python的数据类型
Print (Dict_res)
Print (Type (dict_res))

Output Result:

{' Car3 ': {' color ': ' Red ', ' count ': +, ' price ': ' + ', ' car ': {' color ': ' Red ', ' count ': ', ' ' price ': ' + ', ' car1 ': {' color ' : ' Red ', ' count ': $, ' Price ': 100},

' Car5 ': {' color ': ' Red ', ' count ': ' Price ': ' + ', ' car2 ': {' color ': ' Red ', ' count ': ', ' ' price ': ' + ', ' car4 ': {' color ' : ' Red ', ' count ': $, ' Price ': 100}}
<class ' Dict ' >

3, if you are working with files instead of strings, you can use Json.dump () and Json.load () to encode and decode JSON data

Writing to JSON-formatted files
F1 = open (' F1 ', ' W ', encoding= ' utf-8 ')
Json.dump (d,f1,ensure_ascii=false,indent=4)
#自动帮你写入文件, the first parameter is the data and the second is the file object
Read file
F1 = open (' F1 ', encoding= ' utf-8 ')
Print (Json.load (F1))

Python function Advanced

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.