Reference 1: https://www.cnblogs.com/wujiaqing/p/10709207.html
abs() all() any() bin() bool() bytearray() callable() chr() dict() dir() divmod() enumrate() eval() exec() filter() format() float() frozenset() globals() hasattr() hash() help() hex() id() input() int() isinstance() issubclass() iter() len() list() map() max() min() next() oct() open() ord() pow() print() range() reduce() repr() reversed() round() set() slice() sorted() str() sum() tuple() type() zip() __import__()
1. abs()Function returns the absolute value of a number 2. all() Function is used to determine whether all elements in a given parameter are TRUE, If yes, return True,Otherwise return False. Element except 0, empty None,False Everything else counts True; The return values of empty tuple and empty list are True. 3. any() Function is used to determine whether all the given parameters are False, Yes, return False,If one is True,Then return True. Element except 0, empty False Everything else counts TRUE. 4. bin()Function returns an integer int Or long integer long int Binary representation of 5. bool() The function is used to convert the given parameter to boolean type. If the parameter is not empty or 0, it returns True;If the parameter is 0 or there is no parameter, return False. 6. bytearray()Method returns a new byte array. The elements in this array are variable, and the value range of each element: 0 <= x < 256(I.e. 0-255). Namely bytearray()Is a modifiable binary byte format. 7. callable()Function to check whether an object is callable. For functions, methods lambda Functions, classes, and implementations __call__ Class instance of method, It all returns True. ((anything that can be bracketed can be called) 8. chr()The function uses a range in range(256)Inside (i.e. 0)~255)Returns a corresponding integer as a parameter ASCII Numerical value. 9. dict()Function is used to convert tuples/Convert list to dictionary format. 10. dir()When the function has no parameters, it returns the list of variables, methods and defined types in the current range; With parameters, the list of properties and methods of the parameters is returned. 11. divmod() Function combines the results of divisor and remainder operations and returns a tuple (quotient) containing quotient and remainder x,remainder y). 12. enumerate() Function is used to transfer a traversable data object(Such as list, tuple or string)It is combined into an index sequence and lists data and data subscripts at the same time. It is generally used in for In the cycle. Python 2.3. The above versions are available, 2.6 add to start Parameters. 13. eval() Function is used to execute a string expression and return the value of the expression. 14. exec() Executes a stored in a string or file Python Statement, compared to eval,exec Can perform more complex Python code. 15. filter()It is used to filter the sequence, filter out the unqualified elements, and return an iterator object, which is available list()To convert to a list. be careful: filter()Receive two parameters, the first is a function and the second is a sequence. Each element of the sequence is passed to the function as a parameter for judgment and then returned True or False,Finally, it will return True Put the element in the new list. 16. format()Is a function to format a string. The basic syntax is through {} and : To replace the previous % . format The function can accept unlimited parameters, and the positions can be out of order. 17. float() The function converts integers and strings to floating point numbers. 18. frozenset() Returns a frozen collection (an unordered sequence of non repeating elements). After freezing, no elements can be added or deleted from the collection. 19. globals() The function returns all global variables of the current location in dictionary format. 20. hasattr() Function is used to determine whether an object contains corresponding attributes. If the object has this property, return True,Otherwise return False. 21. hash() Used to get the hash value of an object (number or string, etc.). Cannot be applied directly to list,set,dictionary. Note: in hash() When using an object, the result is not only related to the content of the object, but also related to the content of the object id(),That is, the memory address. 22. help() Function is used to view a detailed description of the purpose of a function or module. 23. hex() Function to convert an integer to a hexadecimal number. Returns a string with 0 x start. 24. id()Function to get the memory address of the object. 25. input() The function accepts a standard input data and returns string Type. This function is the most commonly used. stay Python3.x in raw_input() and input() Consolidated, retaining only input( )Function. 26. int() Function to convert a string or number to an integer. 27. isinstance() Function to determine whether an object is a known type and return a Boolean value. similar type(). isinstance() And type() difference: type() The subclass will not be considered as a parent type, and the inheritance relationship will not be considered. isinstance() You will think that a subclass is a parent type and consider the inheritance relationship. If you want to judge whether the two types are the same, it is recommended to use isinstance(). 28. issubclass()Used to judge parameters class Is it a type parameter classinfo Subclass of. If yes, return True,Otherwise return False. Syntax: issubclass(class,classinfo). 29. iter() Function to generate an iterator. list,tuple And so on are iteratable objects. We can iter()Function to obtain the iterators of these iteratable objects, and then you can continuously use the obtained iterators next()Function to get the next piece of data. iter()A function is actually a function that calls an iteratable object __iter__ method. # Note: when the last data has been iterated, calling the next() function again will throw an exception of StopIteration to tell us that all data have been iterated. 30. len() Method returns the length of an object (character, list, tuple, etc.) or the number of elements. 31. list() Method is used to convert tuples to lists. Note: tuples are very similar to lists. The difference is that the element value of tuples cannot be modified. Tuples are placed in brackets and lists are placed in square brackets. 32. map()Receiving function f and list,And by putting the function f In turn list On each element, get a new one list And return. 33. max()Function returns the maximum value of a given parameter, which can be a sequence. 34. min()Function returns the minimum value of a given parameter, which can be a sequence. 35. next() Returns the next item of the iterator. 36. oct() Function converts an integer to an octal string. 37. open() Function is used to open a file and create a file Object, related methods can call it for reading and writing. 38. ord()Function is chr()Pairing function, which takes one character (string with length of 1) as a parameter and returns the corresponding ASCII Value, or Unicode Value, if given Unicode If the character exceeds the defined range, an error is raised TypeError Exception of. 39. pow()Function return x of y The value of the power. be careful: pow()Call directly through the built-in method. The built-in method will take the parameter as an integer, and math The module converts the parameters into float. 40. print()For printout, the most common function. print stay Python3.x Is a function, but in Python2.x Version is just a keyword. 41. range() Function can create a list of integers, which is generally used in for In circulation. Syntax: range(start, stop[, step]) 42. reduce() The function accumulates the elements in the parameter sequence. stay Python3 ,reduce()Placed in functools In the module, if you want to use it, you need to introduce it first functools modular. 43. repr() Function converts an object to a form that can be read by the interpreter. Returns the of an object string Format. 44. reversed() Function returns an inverted iterator. reversed(seq)The sequence to be converted can be tuple, string, list or range. 45. round() Method returns a floating point number x The rounded value of the. (unless there is no requirement for accuracy, try to avoid using round()Function) 46. set() Function to create an unordered set of non repeating elements. You can test the relationship, delete duplicate data, and calculate intersection, difference, union, etc. 47. slice() Function to realize the slice object, which is mainly used for parameter transfer in the slice operation function. 48. sorted() Function to sort (default ascending order) all iteratable objects. 49. str() Function to convert an object to string Format. 50. sum()Function sums the parameters. 51. tuple()Function converts a list to tuples. # Note: tuples are very similar to lists. The difference is that the element value of tuples cannot be modified. Tuples are placed in brackets and lists are placed in square brackets. 52. type() If you only have the first parameter, the function returns the type of the object, and the three parameters return the new type object. 53. zip() The function is used to take the iteratable object as a parameter, package the corresponding elements in the object into tuples, and then return the object composed of these tuples. The advantage of this is to save a lot of memory. have access to list() Convert to output the list. If the number of elements of each iterator is inconsistent, the length of the returned list is the same as the shortest object. utilize * Number operator, you can decompress the tuple into a list. 54. __import__() Functions are used to dynamically load classes and functions. If a module changes frequently, it can be used __import__() To dynamically load.
Reference 2: http://www.360doc.com/content/19/0228/21/62214076_818220486.shtml
The built-in functions are roughly divided into six categories:
Input / output: print() open() input() Iteration related: enmuerate() zip() Sequence properties: sum() max() min() len() Operation sequence: sorted() reversed() range() Object properties: dir() id() isinstance() type() Mapping type: eval() map() slice()
1, Input and output
1. The print function outputs the object to the console
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
*Objects is a variable parameter and can accept any number of objects. The sep parameter represents the separator between output objects. The default is space.
>>> print('Python', 'Efficient programming') Python Efficient programming
The separator is' * ':
>>> print('Python', 'Efficient programming', sep = '*') Python*Efficient programming
There are three ways to format the output string:
name = 'Python Efficient programming' fmt1 = f'Official account:{name}' fmt2 = 'Official account:{}'.format(name) fmt3 = 'Official account:%s' %name print(fmt1) print(fmt2) print(fmt3) # Official account: Python efficient programming
2. The open function opens the file and returns the file object
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
File is the file address
Mode is the mode of opening the file
The default is' r ', which means to read the file
Commonly used: 'w' means to write to a file
'b' means open in binary form
Open file with common context manager
f.read() reads everything
f.readline() reads a line
with open('test.txt', 'r') as f:
text1 = f.read()
with open('test.txt', 'r') as f:
text2 = ''
line = f.readline()
while line:
text2 += line
line = f.readline()
assert text1 == text2
print(text1)
#Output content: Python efficient programming Python efficient programming Python efficient programming Python efficient programming###############
Sometimes, we will encounter garbled code when reading files. You can specify the encoding format:
When there is Chinese in the file, using 'utf-8' encoding will cause exceptions: Unicode decodeerror: 'utf-8' codec can't decode byte 0xb8 in position 7: invalid start byte
with open('test.txt', 'r', encoding='utf-8') as f:
text1 = f.read()
You can try 'gb2312' or 'gbk' encoding to open files containing Chinese characters. At this point, you can successfully open the file.
with open('test.txt', 'r', encoding='gb2312') as f:
text1 = f.read()
with open('test.txt', 'w', encoding='gbk') as f:
f.write('Python efficient programming ')
3. The input function gets console input
input([prompt])
Input can accept strings as parameters to prompt the user for input.
>>> s = input('Please enter the name of the official account:') Please enter the name of the official account: Python Efficient programming >>> s 'Python Efficient programming'
2, Iterative correlation
1. The enumerate function returns the sequence number and corresponding value of the element
enumerate(iterable, start=0)
The iteratable parameter represents an iteratable object, and the start parameter is the starting point of the element sequence number, which is 0 by default.
The equivalent form of enumerate function is as follows:
def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1 seq = ['P', 'y', 't', 'h', 'o', 'n'] for i, elem in enumerate(seq): print(i, elem)
2. The zip function is used to iterate over multiple objects at the same time
zip(*iterables) *iterable can accept any number of iteratable objects
a = ['**', '**', '**'] b = ['WeChat official account', 'follow', 'Python Efficient programming'] c = a print('#'*20) for i, j, k in zip(a, b, c): print(i, j, k) print('#'*20)
####################
* * WeChat official account * * *
####################
**Attention**
####################
**Python efficient programming**
####################
3, Sequence attribute
Maximum value of sequence: max
Minimum value of sequence: min
sum of sequences: sum
Sequence length: len
Basic usage: pass the sequence into these four functions to get the corresponding attributes.
import random random.seed(21) seq = [random.randint(0, 100) for i in range(10)] print(seq) # [21, 53, 88, 53, 81, 36, 61, 27, 60, 65] print(max(seq)) # 88 print(min(seq)) # 21 print(sum(seq)) # 545 print(len(seq)) # 10
As a built-in function, you can directly pass in the generator (without parentheses) as parameters:
import random random.seed(21) num = max(random.randint(0, 100) for i in range(10)) print(num) # 88
The key parameter can be passed in as the basis for comparing the size, which is equivalent to passing each element item in the sequence into the function key first, and taking the value returned by the function as the basis for judging the size of the object.
def foo(x): return 1. / xmax(seq, key = foo)# 21
For our custom types, we must implement special methods before we can perform operations such as len.
__ len__ Representative: len operation
__ eq__ Representative: = operation
__ lt__ Represents < operation
class foo: def __init__(self, num, seq): self.num = num self.seq = seq def __len__(self): return len(self.seq) def __eq__(self, other): return self.num == other.num def __lt__(self, other): return self.num < other.num >>> f1 = foo(18, [1, 4, 6]) >>> f2 = foo(21, [1, 7, 9, 10]) >>> f1 < f2 True >>> f1 > f2 False >>> f1 == f2 False >>> f3 = foo(18, [9, 9, 0, 7]) >>> f1 == f3 True >>> len(f1) 3 >>> len(f2) 4
4, Operation sequence
1. The range function generates a sequence
range(start, stop[, step])
start is an optional parameter. The default value is 0, indicating the starting point of the sequence
stop is a required parameter, indicating the end point of the sequence, excluding the end point
Step: optional parameter. The step size of the sequence is 1 by default
>>> range(6)range(0, 6) >>> list(range(6)) [0, 1, 2, 3, 4, 5] >>> list(range(0, 6, 2)) [0, 2, 4]
The objects generated by the range function can be iterated, which is very similar to the list_ Represents a waste variable (to avoid polluting the environment):
for _ in range(3): print('Python Efficient programming')
2. The reversed function reverses the sequence
reversed can reverse the sequence, including tuples, strings and lists.
For the inversion of list and string, it is more convenient to use list[::-1] or slice().
import random random.seed(21) seq = [random.randint(0, 100) for i in range(10)] print(seq) # [21, 53, 88, 53, 81, 36, 61, 27, 60, 65] reversed(seq) print(list(reversed(seq))) # [65, 60, 27, 61, 36, 81, 53, 88, 53, 21]
String inversion:
>>> a = 'Python Efficient programming' >>> a[::-1] 'High programming efficiency nohtyP' >>> ''.join(reversed('Python Efficient programming')) 'High programming efficiency nohtyP'
3. The sorted function sorts the sequence
sorted(iterable, *, key=None, reverse=False)
sorted is different from list Sort operation (sort in place) returns a new ordered sequence, and the original sequence remains unchanged.
* indicates only keyword parameters (keyword only), that is, key and reverse parameters can only be passed through keywords, not locations.
The reverse parameter indicates the reverse operation. The key is similar to the key parameter in len and is the basis for sorting functions.
>>> sorted([9, 6, 2, 3, 6]) [2, 3, 6, 6, 9]
5, Object properties
The dir function returns a list of attributes
The id function returns the address of the object
isinstance determines the type of object
Type returns the type of the object
class foo: pass >>> dir(foo) ['__class__', '__delattr__', '__dict__', '__dir__',...... '__str__', '__subclasshook__', '__weakref__'] # Create instance >>> f = foo() >>> type(foo) __main__.foo >>> isinstance(f, foo) True >>> id(f) 2135099584864
6, Mapping type
eval release quotation marks
map functions are applied to a single object
Slice generate slice
1. Eval can remove the single quotation marks of the string to get the contents inside the quotation marks. The following demonstration shows how to use the eval function to get a dictionary in a string:
>>> info = '{'name': 'LiHua', 'age': 12}' >>> eval(info) {'name': 'LiHua', 'age': 12} >>> info_dict = eval(info) >>> type(info_dict) dict
2. map applies the passed function to each element in the sequence and returns the iterator.
map(function, iterable, ...)
For example, a map is an int operation (int(item)) on each element item in the seq list.
Similarly, anonymous functions add 2 to each element in the sequence.
>>> seq = [1.5, 4.5, 9.1] >>> list(map(int, seq)) [1, 4, 9] >>> list(map(lambda x: x + 2, seq)) [3.5, 6.5, 11.1]
3. slice function names slicing operation, which makes slicing operation clearer.
slice(start, stop[, step]): start is the starting point, stop is the end point, and step is the step size.
Using this operation makes it easy to intercept regular text content. Especially for long text, using slice function is clearer and easier to understand.