In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to use Python built-in functions". In daily operation, I believe many people have doubts about how to use Python built-in functions. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to use Python built-in functions". Next, please follow the editor to study!
Abs ()
Returns the absolute value of a number
> abs (- 100,100) > abs (10) 10 > all ()
Determine whether all elements in the given iterable parameter iterable are TRUE, and if True is returned, False is returned.
> all ([100100100]) True > all ([3jin0jin1]) False > any ()
Determines whether the given iterable parameter iterable is all False, returns False, and returns True if one of them is True
> any False > any True > ascii ()
Call the object's repr () method to get the return value of the method
> ascii ('test') "' test'" > bin ()
Convert decimal to binary
> bin (100) '0b1100100' > oct ()
Convert decimal to octal
> oct (100) '0o144' > hex ()
Convert decimal to hexadecimal
> hex (100,0x64' > bool ()
Whether the test object is True or False
> bool (1) True > bool (- 1) True > bool () False > bytes ()
Convert a character to a byte type
> s = "blxt" > bytes (srecoery encodingsounds beautiful utf color 8') baked blxt'> str ()
Convert character and numeric types to string types
> str (123) '123' > callable ()
Check whether an object is callable
False > > callable (str) True > callable (int) True > callable (0) False > chr ()
View the ASCll characters corresponding to decimal integers
> chr (100d' > ord ()
View the decimal system for an ascii
> ord ('a') 97 > classmethod ()
The function corresponding to the modifier does not need to be instantiated or self parameter, but the first parameter needs to be a cls parameter that represents its own class, which can be used to call class properties, class methods, instantiated objects, etc.
#! / usr/bin/python#-*-coding: UTF-8-*-class A (object): bar = 1 def func1 (self): print ('foo') @ classmethod def func2 (cls): print (' func2') print (cls.bar) cls (). Func1 () # call foo method
Output result:
Func21foocompile ()
Compiles the string into code that python can recognize or execute. You can also read the text into a string and compile it.
> blxt = "print ('hello')" > test = compile (blxt,'','exec') > test > exec (test) hello > complex ()
Create a plural
> delattr ()
Delete object properties
#! / usr/bin/python#-*-coding: UTF-8-*-class Coordinate: X = 10 y =-5 z = 0point1 = Coordinate () print ('x =', point1.x) print ('y =', point1.y) print ('z =', point1.z) delattr (Coordinate,'z') print ('--after deleting z attribute -) print ('x =', point1.x) print ('y =' Point1.y) # trigger error print ('z =', point1.z)
Output result:
> x = 10y =-5z = 0Mui-after deleting z attribute-x = 10y =-5Traceback (most recent call last): File "C:\ Users\ fdgh\ Desktop\ test.py", line 22, in print ('z =', point1.z) AttributeError: 'Coordinate' object has no attribute' z' > > dict ()
Create a data dictionary
> dict () {} > dict (axi1dymbund 2) {'aqu: 1, 'baked: 2} > dir ()
Returns a list of variables, methods, and defined types in the current scope when the function takes no arguments
> dir () ['Coordinate',' _ annotations__','_ _ builtins__','_ _ doc__','_ file__','_ loader__','_ name__','_ package__','_ spec__', 'point1','] > divmod ()
Take quotient and remainder respectively
> divmod (11pr 2) (5,1) > enumerate ()
Returns an object that can be enumerated, whose next () method returns a tuple
> blxt = [list (enumerate (blxt)) [(0,'a'), (1,'b'), (2,'c'), (3,'d')] > eval ()
Evaluate the string str as a valid expression and return the calculation result to take out the contents of the string
> blxt = "5 times 1: 2" > eval (blxt) 8 > exec ()
String compiled by executing a string or complie method, with no return value
> blxt = "print ('hello')" > test = compile (blxt,'','exec') > test > exec (test) hello > filter ()
Filter, building a sequence
# filter all odd numbers in the list #! / usr/bin/python#-*-coding: UTF-8-*-def is_odd (n): return n% 2 = = 1newlist = filter (is_odd, [1,2,3,4,5,6,7,8,9,10]) print (newlist)
Output result:
[1,3,5,7,9] float ()
Convert a string or integer to a floating point number
> float (3) 3.0 > float (10) 10.0 > format ()
Format output string
> "{0} {1} {3} {2}" .format ("a", "b", "c", "d")'a b d c'> print ("website name: {name}, address: {url}" .format (name= "blxt", url= "www.blxt.best")) website name: blxt, address: www.blxt.best > frozenset ()
Create an immutable collection
> frozenset ([2, 4, 6, 6, 7, 7, 8, 9]) frozenset ({0,2, 4, 6, 7, 8, 9}) > getattr ()
Get object properties
Class A (object):... Bar = 1... > a = A () > getattr (a, 'bar') # get attribute bar value 1 > getattr (a,' bar2') # attribute bar2 does not exist. Trigger exception Traceback (most recent call last): File ", line 1, in AttributeError:'A 'object has no attribute' bar2' > getattr (a, 'bar2', 3) # attribute bar2 does not exist, but the default value 3 > globals () is set.
Returns a dictionary that describes the current global variable
The print (globals ()) # globals function returns a dictionary of global variables, including all imported variables. {'_ _ builtins__':,'_ _ name__':'_ _ main__','_ _ doc__': None, 'runoob',' _ _ package__': None} hasattr ()
Function is used to determine whether the object contains the corresponding attribute
Class A (object):... Bar = 1... > a = A () > hasattr (a recorder bar') True > hasattr (a recorder test') Falsehash ()
Returns the hash value of the object
Class A (object):... Bar = 1... > a = A () > hash (a)-2143982521 > help ()
Returns the help document for the object
Class A (object):... Bar = 1... > a = A () > > help (a) Help on An in module _ _ main__ object:class A (builtins.object) | Data descriptors defined here: | | _ _ dict__ | dictionary for instance variables (if defined) | | _ _ weakref__ | list of weak references to the object (if defined) | |-- -| Data and other attributes defined here: | | bar = 1 > id ()
Returns the memory address of the object
Class A (object):... Bar = 1... > a = A () > id (a) 56018040 > input ()
Get user input
Input (). Test'test' > > int ()
Used to convert a string or number to an integer
> int 20 > int 12 > int 14 > isinstance ()
To determine whether an object is of a known type, similar to type ()
> test = 100 > isinstance (test,int) True > isinstance (test,str) False > issubclass ()
Used to determine whether the parameter class is a subclass of the type parameter classinfo
#! / usr/bin/python#-*-coding: UTF-8-*-class A: passclass B (A): passprint (issubclass (BMague A)) # returns Trueiter ()
Returns an iterable object that can be omitted by sentinel
> lst = [1,2,3] > for i in iter (lst):. Print (I)... 123len ()
Returns the length of the object
> dic = {'axiaqizhuo 100jinghuanglu 200} > len (dic) 2 > list ()
Returns a variable sequence type
> a = (123 map) > list (a) [123 procession] >
Returns an iterator that applies function to each item in iterable and outputs its results
> def square (x): # calculate the square. Return x * * 2... > map (square, [1gime 2jin3, 4je 5]) # calculates the square of each element of the list [1,4,9,16,25] > map (lambda x: X * * 2, [1Jing 2Jing 3Jing 4Jing 5]) # provides two lists using the lambda anonymous function [1,4,9,16,25] # Add list data in the same location > map (lambda x, y: X + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]) [3, 7, 11, 15, 19] max ()
Return the maximum value
> max (1, min, 3, 4, 5, 6, 7, 8, 9)
Return to the minimum
> min (1 > memoryview ()
Returns the memory view object (memory view) for the given parameter
> > v = memoryview (bytearray ("abcefg", 'utf-8')) > print (v [1]) 98 > print (v [- 1]) 103 > print (v [1:4]) > print (v [1:4]. Tobytes ()) bauxbce' > next ()
Returns the next element of an iterable object
> a = iter > > next (a) 1 > > next (a) 2 > next (a) 3 > next (a) 4 > next (a) 5 > next (a) Traceback (most recent call last): File ", line 1, in next (a) StopIteration > object ()
Returns a new object without features
> a = object () > type (a) > open ()
Returns the file object
> f = open ('test.txt') > f.read ()' 123/123/123'pow ()
Base is the exp power of the base, if mod gives, take the remainder.
> pow (3 and 1) 3 > print ()
Print object
Class property ()
Returns the property property
Class C (object): def _ init__ (self): self._x = None def getx (self): return self._x def setx (self, value): self._x = value def delx (self): del self._x x = property (getx, setx, delx, "Ihumm the'x 'property.") range ()
Generate an immutable sequence
> range (10) range (0,10) > reversed ()
Returns a reverse iterator
> a = 'test' > print (list (reversed (a) [' t','s', 'eBay,' t'] > > round ()
Round off
> round (3.3333333) > round ()
Returns a set object that can be de-duplicated
> a = [1, set, 2, 3, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5] > set (a) {1, 2, 3, 4, 6} > class slice ()
Returns a slice object that represents the index set specified by 1range
> a = [1, slice, 4, 5, 5, 5, 6, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
Sort all iterable objects
> a = [1, sorted, 4, 4, 5] > @ staticmethod
Convert a method to a static method
#! / usr/bin/python#-*-coding: UTF-8-*-class C (object): @ staticmethod def f (): print ('blxt'); C.F (); # static methods can be called after instantiation without instantiating cobj = C () cobj.f () #
Output result:
Test testsum ()
Summation
A = [1, sum 2, 3, 4, 5, 5, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2] > sum (a) 40 > super ()
Returns a proxy object
Class A: def add (self, x): y = print (y) class B (A): def add (self, x): super () .add (x) b = B () b.add (2) # 3tuple ()
Immutable sequence type
> a = 'www' > b = tuple (a) > b (' wicked, 'wicked,' w') > zip ()
Take iterable objects as parameters, package the corresponding elements in the object into tuples, and then return a list of these tuples
> a = [1pje 2pr 3] > b = [4pje 5je 6] > > c = [4pje 5pje 6je 7je 8] > > zipped = zip (arem b) # list packaged into tuples [(1,4), (2,5), (3,6)] > zip (aPowerc) # the number of elements is consistent with the shortest list [(1,4), (2,5), (3) 6)] > zip (* zipped) # is opposite to zip * zipped can be understood as decompression and return to the two-dimensional matrix [(1, 2, 3), (4, 5, 6)]. At this point, the study on "how to use Python built-in functions" is over. I hope to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.