Overview of built-in functions
There are 80 built-in functions in Python 2.7. Skillfully remembering and using these built-in functions will greatly improve the speed of writing Python code and the elegance of the code.
The following code example uses ipython, a much better interpreter than the official interpreter, to learn and use values.
Math related built-in functions
- abs(x) returns the absolute value of a number
In [18]: abs(3.14) Out[18]: 3.14 In [19]: abs(-3.14) Out[19]: 3.14
- complex(real[, imag]) generates a complex number
In [135]: complex(1,3) Out[135]: (1+3j)
- divmod(x, y) returns the quotient and remainder of X divided by y
In [143]: divmod(12, 7) Out[143]: (1, 5)
- max(iterable[, key]) returns the largest element of a sequence
In [157]: max([(1,2,3), (4,5,6), (23,4,1,)], key=lambda a: a[-1]) Out[157]: (4, 5, 6) In [158]: max(1,2,3,4,4,5) Out[158]: 5 In [159]: max([(1,2,3), (4,5,6), (23,4,1,)]) Out[159]: (23, 4, 1) In [160]: max([(1,2,3), (4,5,6), (23,4,1,)], key=lambda a: a[-1]) Out[160]: (4, 5, 6) In [161]: max([{'age':10, 'name': 'aaa'}, {'age': 12, 'name': 'bb'}], key=lambda a: a['age']) Out[161]: {'age': 12, 'name': 'bb'}
- min(iterable[, key]) returns the smallest element of a sequence
- See the max() function above
- pow(x, y[, z]) returns the y-power of X. if there is a parameter Z, it returns the remainder of the power divided by Z (modulo z)
In [166]: pow(2,3) Out[166]: 8 In [167]: pow(2,3,5) Out[167]: 3
- round(number[, ndigits]) returns the rounded value of a number. Given ndigits, it is rounded to the nth decimal place
In [170]: round(3.45) Out[170]: 3.0 In [171]: round(3.55) Out[171]: 4.0 In [172]: round(3.55345, 3) Out[172]: 3.553
sum(sequence[, start]) sums a number sequence. Start is the starting position. It starts from 0 by default. Finally, if your time is not very tight and you want to improve python quickly, the most important thing is not afraid of hardship. I suggest you can build a micro platform ♥ Letter: 2763177065, that's really good. Many people make rapid progress. You need to be not afraid of hardship! You can add it and have a look~
In [175]: sum([1,2,3,4]) Out[175]: 10
Number and character conversion
- bin(number), hex(number), oct(number)
- Convert a number into binary, hexadecimal, octal string
In [204]: print bin(20), hex(16), oct(9) 0b10100 0x10 011
- bool(x) returns True if x is True, False otherwise
In [184]: print bool(3), bool('a') True True In [185]: print bool(0), bool(''), bool(None) False False False
- chr(i) converts an integer to ascii characters, 0 < = I < 256
In [188]: chr(320) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-188-5b2996ffe50c> in <module>() ----> 1 chr(320) ValueError: chr() arg not in range(256) In [189]: chr(65) Out[189]: 'A' In [190]: chr(0) Out[190]: '\x00'
- unichr(i) converts an integer to Unicode characters, 0 < = I < = 0x10ffff
In [225]: unichr(1245) Out[225]: u'\u04dd'
- ord © Convert an ascii character to an integer
In [192]: ord('a') Out[192]: 97 In [193]: ord('\x23') Out[193]: 35
- float(x), int(x), long(x) conversion between floating point numbers, integers, and long integers
In [196]: print float('13'), float(13) 13.0 13.0 In [197]: print int('14'), int(14) 14 14 In [198]: print long('15'), long(15) 15 15
- format(value[, format_spec]) use format for value_ Spec format
In [212]: format(123, '05d') Out[212]: '00123'
The above is equivalent to print '% 05d'% 123
- hash(ojbect) calculates the hash value of the object
In [218]: hash(123) Out[218]: 123 In [219]: hash('abc') Out[219]: 1453079729188098211
- str(object = '') converts an object into a string:
In [221]: str(123) Out[221]: '123' In [222]: str([1,2,3]) Out[222]: '[1, 2, 3]' In [223]: str({'a': 1, 'b': 2}) Out[223]: "{'a': 1, 'b': 2}"
Input and output
- file(name[, mode[, buffering]]), open to open a file
In [251]: file('abc.txt', 'w') Out[251]: <open file 'abc.txt', mode 'w' at 0x7f93e727a660> In [252]: open('abc.txt', 'w') Out[252]: <open file 'abc.txt', mode 'w' at 0x7f93e727a780>
- input([prompt]), raw_input() inputs information from the terminal
In [253]: input('pls input a number >>') pls input a number >>123 Out[253]: 123
Sequence processing
- all(iterable) returns True if all values of a sequence are True; otherwise, returns False
- any(iterable) returns True if at least one of a sequence is True, otherwise False
In [255]: all([1,2,3,4]) Out[255]: True In [256]: all([1,2,3,4, 0]) Out[256]: False In [257]: any([1,2,3,4, 0]) Out[257]: True
- enumerate(iterable[, start]) traverses a sequence of elements and their indexes
In [261]: for i, value in enumerate(['a', 'b', 'c']): .....: print i, value .....: 0 a 1 b 2 c
- Filter (function or none, quantity) returns elements that satisfy that function(item) is True
In [263]: filter(lambda x: x>3, [1,2,3,4,5]) Out[263]: [4, 5]
- iter(collection) returns the iterator of an object
It is useful when reading files:
with open("mydata.txt") as fp: for line in iter(fp.readline, "STOP"): process_line(line)
- len(object) returns the number of elements of an object
In [267]: len('abc'), len([1,2,3]) Out[267]: (3, 3)
- map(function, sequence[, sequence,...]) applies a function to each element and returns a list
In [269]: map(lambda x: x+3, [1,2,3]) Out[269]: [4, 5, 6] In [270]: a = [1,2]; b = ['a', 'b']; c = ('x', 'y') In [271]: map(None, a, b, c) Out[271]: [(1, 'a', 'x'), (2, 'b', 'y')]
- reduce(function, sequence[, sequence,...]) applies the function to the initial two elements, calls the function with the return value and the next element as input, and iterates all elements in turn
In [281]: reduce(lambda a, b: a-b, [1,2,3]) Out[281]: -4
- zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
- Merge multiple sequences into one sequence list
- sorted(iterable, cmp=None, key=None, reverse=False) sorts a sequence
In [283]: zip([1,2,3], ('a', 'b', 'c')) Out[283]: [(1, 'a'), (2, 'b'), (3, 'c')] range() xrange() Returns a sequence of integers In [274]: [x for x in xrange(10)] Out[274]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] In [275]: [x for x in xrange(5, 10)] Out[275]: [5, 6, 7, 8, 9] In [276]: [x for x in xrange(5, 10, 2)] Out[276]: [5, 7, 9] In [277]: range(10) Out[277]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] In [278]: range(5, 10) Out[278]: [5, 6, 7, 8, 9] In [279]: range(5, 10, 2) Out[279]: [5, 7, 9]
Optional parameters cmp, key, reverse and list The parameters of the sort () method have the same meaning (described in the variable sequence types section).
cmp specifies a custom comparison function (iteratable element) with two parameters. It should return negative, zero or positive numbers according to whether the first parameter is less than, equal to or greater than the second parameter: cmp=lambda x,y: cmp(x.lower(), y.lower()). The default value is None.
Key specifies a function with one parameter, which is used to select a keyword for comparison from each list element: key=str.lower. The default value is None (direct comparison of elements). Finally, if you are not very nervous about your time and want to improve python quickly, the most important thing is not afraid of hardship. I suggest you can build a micro platform ♥ Letter: 2763177065, that's really good. Many people make rapid progress. You need to be not afraid of hardship! You can add it and have a look~
Reverse is a Boolean value. If set to True, the list elements are sorted by reverse comparison.
In general, the key and reverse conversion process is much faster than specifying an equivalent CMP function. This is because CMP calls each element multiple times, but key and reverse touch each element only once. Use functools cmp_ to_ Key() to convert the old CMP function into a key function.
In [288]: sorted(d.items(), key=lambda a: a[1]) Out[288]: [('a', 3), ('b', 4)] In [289]: sorted(d.items(), key=lambda a: a[1], rev) In [289]: sorted(d.items(), key=lambda a: a[1], reverse=True) Out[289]: [('b', 4), ('a', 3)] In [290]: sorted(d.items(), cmp=lambda a, b: cmp(a[1], b[1])) Out[290]: [('a', 3), ('b', 4)]
data structure
bytearray() dict() frozenset() list() set() tuple()
The common data structures in python are list, dict, set and tuple
Object, type
The following are some functions related to class es and types, which are not commonly used. You can check the manual for details.
basestring() callable() classmethod() staticmethod() property() cmp() compile() delattr() getattr() setattr() hasattr() dir() globals() locals() vars() help() id() isinstance() issubclass() object() memoryview() repr() super() type() unicode() import() eval() execfile()
Unimportant built-in functions
apply() buffer() coerce() intern()
ipython
ipython is a very good interactive python interpreter. It can check the usage of a function or class by:
- help(xxx)
- xxx?
- When viewing member functions or variables of a class / object, enter after the class or object variable Press tab after:
In [292]: import time In [293]: time. time.accept2dyear time.clock time.gmtime time.sleep time.struct_time time.tzname time.altzone time.ctime time.localtime time.strftime time.time time.tzset time.asctime time.daylight time.mktime time.strptime time.timezone In [293]: time.ti time.time time.timezone In [293]: time.time? Docstring: time() -> floating point number Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them. Type: builtin_function_or_method
On the way of learning Python, we often encounter many problems, but the problem we have together is not a problem. We can find Nordic DA in Xiaobian and study together. We can also get learning dry goods by private letter "01". If you encounter any problems, you can ask Xiaobian DA in time.