程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python basics 012] detailed understanding of anonymous functions and all built-in functions (Part 2)

編輯:Python

Catalog

️ Preface

One 、reversed Built in functions

Two 、slice Built in functions

3、 ... and 、format Built in functions

Four 、bytes Built in functions

5、 ... and 、bytearray Built in functions

6、 ... and 、memoryview Built in functions

7、 ... and 、ord、chr and ascii Built in functions

8、 ... and 、repr Built in functions

Nine 、enumerate Built in functions

Ten 、all and any Built in functions

11、 ... and 、zip Built in functions

Twelve 、filter and map Built in functions

1、filter Built in functions

2、map Built in functions

3、 summary

13、 ... and 、sorted Built in functions

fourteen 、 Anonymous functions

️ Conclusion


Preface

What I want to explain below is Python The last remaining important built-in functions in , The more important ones will be explained in detail , Relatively simple, it will be analyzed directly in combination with the code

One 、reversed Built in functions

describe
reversed Function returns an inverted iterator .

grammar

reversed(seq)
Parameters
seq -- The sequence to convert , It can be tuple, string, list or range.
Return value
Returns an inverted iterator .

# Use reverse The original list is gone
l = [1,2,3,4,5]
l.reverse()
print(l)
# Keep the original list , Returns a reverse iterator
l = [1,2,3,4,5]
l2 = reversed(l)
print(l2)
Output solution :
[5, 4, 3, 2, 1]
<list_reverseiterator object at 0x000001BF41858F40>

Two 、slice Built in functions

describe
slice() Function to implement slicing objects , It is mainly used for parameter passing in slice operation function .

grammar
slice grammar :

class slice(stop)
class slice(start, stop[, step])
Parameter description :

start -- The starting position
stop -- End position
step -- spacing
Return value
Returns a slice object .

l = (1,2,3,4,5,6)
# First, we get a slicing rule
sli = slice(1,5,2)
# Slice according to the rules
print(l[sli])
Output results :
(2, 4)

3、 ... and 、format Built in functions

Knowledge point :http://t.csdn.cn/Onubp

Four 、bytes Built in functions

describe
bytes Function returns a new bytes object , The object is a 0 <= x < 256 An immutable sequence of integers in an interval . It is bytearray The immutable version of .

grammar
Here are bytes The grammar of :

class bytes([source[, encoding[, errors]]])
Parameters
If source Integers , Returns a length of source Initialize the array of ;
If source For the string , As specified encoding Converts a string to a sequence of bytes ;
If source Is an iterable type , The element must be [0 ,255] The integer ;
If source As with the buffer An object with a consistent interface , This object can also be used for initialization bytearray.
If no parameters are entered , The default is to initialize the array as 0 Elements .
Return value
Back to a new bytes object .

Be careful :

Network programming can only transmit binary

Photos and videos are also stored in binary

html What the web crawls to is also the code

# What I got was gbk Coded , I want to change to utf-8 code
print(bytes(' Hello ',encoding='gbk').decode('gbk'))
#unicode Convert to utf-8 Of bytes
print(bytes(' Hello ',encoding='utf-8'))
Output results :
Hello
b'\xe4\xbd\xa0\xe5\xa5\xbd'

5、 ... and 、bytearray Built in functions

describe
bytearray() Method returns a new byte array . The elements in this array are mutable , And the range of values for each element : 0 <= x < 256.

grammar
bytearray() Method syntax :

class bytearray([source[, encoding[, errors]]])
Parameters
If source Integers , Returns a length of source Initialize the array of ;
If source For the string , As specified encoding Converts a string to a sequence of bytes ;
If source Is an iterable type , The element must be [0 ,255] The integer ;
If source As with the buffer An object with a consistent interface , This object can also be used for initialization bytearray.
If no parameters are entered , The default is to initialize the array as 0 Elements .
Return value
Returns a new byte array .

b_array = bytearray(' Hello ',encoding='utf-8')
print(b_array)
print(b_array[0])
Output results :
bytearray(b'\xe4\xbd\xa0\xe5\xa5\xbd')
228

6、 ... and 、memoryview Built in functions

describe
memoryview() Function returns the memory view object with the given parameter (memory view).

So called memory view object , Wrap the data that supports the buffer protocol , Allows without the need to copy objects Python Code access .

grammar

memoryview(obj)
Parameter description :

obj -- object
Return value
Returns a list of tuples .
 

# section —— Byte type slices
v = memoryview(bytearray("abcd", 'utf-8'))
print(v[1])
Output results :
98

7、 ... and 、ord、chr and ascii Built in functions

#ord Follow the characters unicode Turn numbers
>>>print(ord('a'))
>>>print(ord('A'))
>>>print(ord('1'))
97
65
49
#chr The figures are in accordance with unicode Transfer characters
>>>print(chr(65))
>>>print(chr(97))
A
a
#ascii As long as it is ASCII The contents of the code will be printed , If not, it will be converted to \u
#ascii Include letters 、 Numbers 、 Symbol 、 Latin
>>>print(ascii(' Hello '))
>>>print(ascii(1))
>>>print(ascii("_12"))
>>>print(ascii('a'))
'\u4f60\u597d'
1
'_12'
'a'

8、 ... and 、repr Built in functions

describe
repr() Function to convert an object into a form for the interpreter to read .

grammar
Here are repr() The grammar of the method :

repr(object)
Parameters

object -- object .
Return value

Returns the string Format .

# You can judge what type of data the console outputs
print(repr('1'))
print(repr(1))
Output results :
'1'
1

Nine 、enumerate Built in functions

describe
enumerate() Function is used to traverse a data object ( As listing 、 Tuples or strings ) Combined into an index sequence , List both data and data index , Generally used in for Cycle of .

grammar
Here are enumerate() The grammar of the method :

enumerate(sequence, [start=0])
Parameters
sequence -- A sequence 、 Iterators or other objects that support iteration .
start -- Subscript start position .
Return value
return enumerate( enumeration ) object .

lst = ['a','b','c']
print(list(enumerate(lst)))
for i in enumerate(lst):
print(i)
Output results :
[(0, 'a'), (1, 'b'), (2, 'c')]
(0, 'a')
(1, 'b')
(2, 'c')

Ten 、all and any Built in functions

  • all: Used to judge a given Iterative parameter iterable Whether all elements in have bool The value is False, Return if any True, Otherwise return to False. Except that the elements are 0、 empty 、None、False Outside is True.
  • any: be used for Determine the given iteratable parameter iterable Is there a bool The value is True The elements of , If I have a theta True, If there is no one, return False. Except that the elements are 0、 empty 、FALSE Outside is TRUE.
print(all([1,'','a']))
print(all([1,'a']))
print(all([0,123]))
Output results :
False
True
False
print(any(['','Ture',123]))
print(any(['',0]))
Output results :
True
False

11、 ... and 、zip Built in functions

describe
zip() Function to take iteratable objects as parameters , Package the corresponding elements in the object into tuples , And then return the objects made up of these tuples , The advantage is that it saves a lot of memory .

We can use list() Convert to output list .

If the number of elements in each iterator is inconsistent , Returns a list of the same length as the shortest object , utilize * The operator , Tuples can be unzipped into lists .

zip Method in Python 2 and Python 3 Different in : stay Python 2.x zip() It returns a list .

grammar
zip grammar :

zip([iterable, ...])
Parameter description :

iterabl -- One or more iterators ;
Return value
Return an object .

l1 = [1,2,3]
l2 = ['a','b','c','d']
l3 = [{1,2},'**']
print(zip(l1,l2))
for i in zip(l1,l2):
print(i)
print("=======================")
for i in zip(l1,l2,l3):
print(i)
Output results :
<zip object at 0x000001967CE0B600>
(1, 'a')
(2, 'b')
(3, 'c')
=======================
(1, 'a', {1, 2})
(2, 'b', '**')

Twelve 、filter and map Built in functions

1、filter Built in functions

filter() Function to filter the sequence , Filter out the elements that do not meet the conditions , Returns an iterator object , If you want to convert to a list , have access to list() To convert .

This accepts two parameters , The first one is a function , The second is the sequence , Each element of the sequence is passed to the function as a parameter to be judged , Then return True or False, And then it will return True Is placed in the new list .

def is_odd(x):
return x % 2 == 1
ret = filter(is_odd,[1,2,4,7,9])
print(ret)
print([i for i in ret])
Output results :
<filter object at 0x000001FF38B48640>
[1, 7, 9]

2、map Built in functions

map() Function will map the specified sequence according to the function provided .

The first parameter function Call... With each element in the parameter sequence function function , Return contain every time function The function returns a new list of values .

ret = map(abs,[1,-4,6,-9])
print(ret)
print([i for i in ret])
Output results :
<map object at 0x000001CF1D7C90A0>
[1, 4, 6, 9]

3、 summary

    filter   Yes filter The number of elements in the subsequent result set <= The number before execution
            filter Just sift , The original value will not be changed before and after execution
    map     The number of elements remains unchanged before and after execution
            map The original value may change before and after execution

13、 ... and 、sorted Built in functions

sorted Built in functions :

fourteen 、 Anonymous functions

Anonymous functions : A one sentence function designed to meet the needs of simple functions

 

 

# Make the following functions anonymous
def add1(x,y):
return x + y
add2 = lambda x,y : x + y
print(add1(1,3))
print(add2(2,4))
Output results :
4
6

Conclusion

Thank you for seeing here : In an unpublished article, Lu Xun said :“ If you understand the code, you must operate it yourself, so that you can better understand and absorb .”
One last sentence : A man can succeed in anything he has unlimited enthusiasm , Let's make progress together

 

 


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved