In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "what are the similarities between Python and JS". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Data type
In Python, the most commonly used data types that can be processed directly are as follows:
Numbers [integer (int), floating point (float), long integer (long), plural (complex)]
String (str)
Boolean value (bool)
Null value (None)
In addition, Python provides a variety of data types such as lists [list], dictionaries [dict], and so on, which are described below.
Type conversion and Type judgment
Much like JS, python can also implement forced and implicit conversions between different data types, as shown in the following example:
Cast:
Int ('3') # 3str (3.14) # '3.14'float (' 3.14') # 3.1 is different from JS only one type of Number, different types of numbers in Python can also be forced to convert float (3) # 3.0bool (3) # Truebool (0) # False
Implicit type conversion:
1 "1" 2.01+False# 11.0+True# 2 "is different from JS's String + Number = String. Str + int in py will report an error" 1 "1" # TypeError: cannot concatenate 'str' and' int' objects.
In addition, you often need to determine the type of value when writing code. You can use the type () function provided by python to get the type of variable, or use isinstance (x, type) to determine whether x belongs to the corresponding type type.
Type = = float# Trueisinstance ('averse, str) # Trueisinstance (1.3 Falseisinstance (True,bool) # Trueisinstance ([], list) # Trueisinstance ({}, dict) # True ordered collection type
A set is a data structure that contains a set of elements. the elements in an ordered set are arranged in order. There are probably the following categories of ordered sets in Python: list, tuple, str, unicode.
List Typ
The List type in Python is similar to Array in JS.
There is no one to answer the question? The editor has created a Python learning exchange QQ group: 857662006 look for like-minded partners to help each other, and there are also good video learning tutorials and PDF e-books in the group! L = [1 hi', 2 3'L.append 3] print L [- 1] # 'print (4) # add element print L # [1 print 2 Magee 3, 4] L.insert (0 print 3) # at the end of the specified index position to add the element L.pop L # [' 1 2 print 3, 4] L.pop () # at the end remove the element L.pop (2)??
The tuple type is another ordered list, translated as "tuple" in Chinese. Tuple is very similar to list, but once the tuple is created, it cannot be modified.
T = (1) print t [0] # 1 t [0] = 1 TypeError: 'tuple' object does not support item assignmentt = (1) print t # 1t the result is the integer 1t = (1,) # in order to avoid the ambiguous single element tuple, Python stipulates that the single element tuple should add an extra comma "," print t # (1,) unordered set type dict type "
The dict type in Python is similar to {} in JS (the biggest difference is that it is out of order) and has the following characteristics:
Search speed is fast (whether dict has 10 elements or 100000 elements, the search speed is the same)
Large memory footprint (as opposed to list type)
Key in dict cannot be repeated
Key-value order pairs stored in dict are out of order
There is no one to answer the question? The editor has created a Python learning exchange QQ group: 857662006 look for like-minded partners to help each other, and there are also good video learning tutorials and PDF e-books in the group! D = {'aura dictfor key,value in d.items 1,' baggage key,value 2, 'cantilevered print 3} 2set d # {' axiajuv1, 'cantilev 3,' cantilev 2} you can see that the printed pairs are not typed in the normal order # ergodic (): print ('% s:% slots% (key,value)) # a: printed c: printed b: 2set type
Sometimes all we want is the key of dict, we don't care about the value corresponding to key, and we want to make sure that the elements of the collection are not repeated, then the set type comes in handy. The set type has the following characteristics:
The element stored by set is similar to the key of dict and must be an immutable object
The elements stored in set are also out of order
S = set (['Amish recorder' Che']) print s # set ([''Amish' 'Che' B']) s.add ('D') print s # set ([''Amur' Che'']) s.remove ('D') print s # set ([''Atom' Che']) Python
After introducing the types of ordered and unordered sets in Python, there must be a for loop that traverses the set. But unlike standard for loops in other languages, all iterations in Python are done through for. It's done by in. Here are some common iterative demos:
Index iteration:
L = ['apple','banana','orange'] for index, name in enumerate (L): # enumerate () function turns [' apple','banana','orange'] # into a form like [(0, 'apple), (1,' banana'), (2, 'orange')] print index,'-', name# 0-apple# 1-banana# 2-orange
Value of iterative dict:
There is no one to answer the question? The editor has created a Python learning exchange QQ group: 857662006 look for like-minded partners to help each other, and there are also good video learning tutorials and PDF e-books in the group! D = {'apple':6,'banana':8,'orange':5} print d.values () # [6, 8, 5] for v in d.values () print v5
Iterate through the key and value of dict:
D = {'apple':6,'banana':8,'orange':5} for key, value in d.items () print key,':', value# apple: "banana:" orange: 5 slice operator
The slicing operator provided by Python is similar to the native function slice () provided by JS. With the slicing operator, some operations that used to use loops are greatly simplified.
L = ['apple','banana','orange','pear'] L [0:2] # [' apple','banana'] take the first two elements L [: 2] # ['apple','banana'] if the first index is 0, you can omit L [:] # [' apple','banana','orange','pear'] with only one: From beginning to end, the third parameter L [:: 2] # ['apple',' orange'] takes one for every N, which means that from scratch, one out of every 2 elements is taken to the list generator.
What if you want to generate [1x1, 2x2, 3x3,..., 10x10]? The first method is to cycle:
L = [] for x in range (1m 11): L.append (x * x)
But the loop is too tedious, and the list generator can generate the above list with one line instead of the loop:
# put the element x * x to be generated in front, followed by a for loop, and you can create the list [x * x for x in range (1d11)] # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
The for loop of list generation can also be followed by if judgment (similar to the filter () function in JS). The example is as follows:
[X * x for x in range (1m 11) if x% 2pm 0] # [4,16,36,64,100]
For loops can be nested, so in list generation, you can also use multi-tier for loops to generate lists.
[M + n for m in'ABC'for n in'123'] # ['A1,'A2,'A3,'B1, B2, B3, C1, C2, C3] default parameters of the Python function
The default parameter of ES6 in JS is borrowed from Python and is used as follows:
There is no one to answer the question? The editor has created a Python learning exchange QQ group: 857662006 look for like-minded partners to help each other, and there are also good video learning tutorials and PDF e-books in the group! Def greet (name='World'): print'Hello,'+ name +'. 'greet () # Hello, World.greet (' Python') # Hello, Python. Variable parameter
Similar to automatically identifying the number of incoming parameters in the JS function, Python also provides the definition of variable parameters, that is, preceded by a * sign before the name of the variable parameter.
Def fn (* args): print argsfn () # () fn ('a`) # ('axim,) fn (' axie dagger') # ('axie daijia')
The Python interpreter assembles the passed-in set of parameters into a tuple and passes them to the variable, so inside the function, just think of the variable args as a tuple.
Commonly used higher order functions
The functions commonly used in Python (map, reduce, filter) are the same as in JS, but slightly different.
Map function: receives a function f and a list, and by acting the function f on each element of the list in turn, gets a new list and returns.
Def f (x): return x * xprint map (f, [1, 4, 2, 3, 5, 5, 6, 7, 8, 9]) # [1,4,9,16,25,36,49, 64, 81]
Reduce function: receives a function f and a list (you can accept a third value as the initial value). Reduce () repeatedly calls function f for each element of list and returns the final result value.
Def f (x, y): return x * yreduce (f, [1meme 3pm 5]) # 15
Filter function: receives a function f and a list, the function of this function f is to judge each element, return True or False,filter () automatically filter out the elements that do not meet the criteria according to the judgment result, and return the new list composed of qualified elements.
There is no one to answer the question? The editor has created a Python learning exchange QQ group: 857662006 look for like-minded partners to help each other, and there are also good video learning tutorials and PDF e-books in the group! Def is_odd (x): return x% 2==1filter (is_odd, [1, 4, 6, 7, 9, 12, 17]) # [1, 7, 9, 17] anonymous functions
Unlike JS's anonymous function, Python's anonymous function can only have one expression and cannot write return. Take the map () function as an example:
Map (lambda x: X * x, [1 lambda 2, 3 4, 4 5, 6 7, 8 8]) # [1, 4, 9, 16, 25, 36, 49, 64, 81]
The keyword lambda indicates an anonymous function, and the x before the colon represents the function parameter. You can see that the anonymous function lambda x: X * x is actually:
Def f (x): return x * x closure
I have written some articles about JS closures, such as JavaScript closures (Closure), and reading notes-you don't know JavaScript (above). The definition of closures in Python is consistent with that in JS, that is, the inner function refers to the variables of the outer function, and then returns the inner function. Let's take a look at the classical problem of the for cycle of closures in Py:
There is no one to answer the question? The editor has created a Python learning exchange QQ group: 857662006 look for like-minded partners to help each other, and there are also good video learning tutorials and PDF e-books in the group! # hoping to return three functions at a time, respectively calculating 1x1 fs.append 2x2 count (): fs = [] for i in range (1jue 4): def f (): return I * I fs.append (f) return fsf1, f2, f3 = count () # this is equivalent to the deconstruction assignment print F1 (), f2 (), f3 () # 9 9 9 in ES6
The old question, F1 (), f2 (), f3 (), shouldn't the result be 1, 4, 9, why are the actual results all 9?
The reason is that when the count () function returns three functions, the value of the variable I referenced by the three functions has become 3. Since F1, f2, and f3 are not called, they do not calculate the ideteci at this time. When F1 is called, I has already become 3.
To use closures correctly, make sure that referenced local variables do not change after the function returns. The code is modified as follows:
Method 1: it can be understood as creating a closed scope. After the value of I is passed to j, it has nothing to do with I. The closure formed by each loop is stored in memory.
Def count (): fs = [] for i in range (1Jing 4): def f (j): def g (): # method-return j * j return g r = f (I) fs.append (r) return fsf1, f2, f3 = count () print F1 (), f2 (), f3 () # 1 49
Method 2: the idea is more ingenious, using the default parameter j in the function definition can get the value of I, although there is no closure, but there are similarities and differences with method one.
There is no one to answer the question? The editor has created a Python learning exchange QQ group: 857662006 look for like-minded partners to help each other, and there are also good video learning tutorials and PDF e-books in the group! Def count (): fs = [] for i in range (1Mague 4): def f (j = I): # method II return j * j fs.append (f) return fsf1, f2, f3 = count () print F1 (), f2 (), f3 () # 1 4 9decorator decorator
Decorator in the grammar of ES6 is borrowed from decorator of Python. Decorator is essentially a higher-order function that takes a function as an argument and returns a new function.
What is the function of the decorator? Let's start with the gateway code written in ts in the previous daily project:
@ Post ('/ rider/detail') / / URL routing @ log () / print log @ ResponseBody publicasync getRiderBasicInfo (@ RequestBody ('riderId') riderId: number, @ RequestBody (' cityId') cityId: number,) {const result = awaitthis.riderManager.findDetail (cityId, riderId) return result}
You can see that using decorators can greatly simplify the code and avoid writing repetitive code for each function (such as logging, routing, performance testing).
Back on Python, the @ syntax provided by Python uses decorator, which is equivalent to f = decorate (f). Let's look at the implementation of @ log () in Python:
There is no one to answer the question? The editor has created a Python learning exchange QQ group: 857662006 look for like-minded partners to help each other, and there are also good video learning tutorials and PDF e-books in the group! # We want to print out the name of the called function @ log () def factorial (n): return reduce (lambda xperiary y: Xperiy, range (1) Print factorial (10) # look at the definition of @ log () def log (): def log_decorator (f): def fn (x): print' called the function'+ f.roomnameprogramming _ + 'return f (x) return fn return log_decorator# result # called the function factorial () # 3628800class face-to-object programming
Object-oriented programming is a programming paradigm, the basic idea is: define abstract types with classes, and then create instances according to the definition of classes. On the basis of mastering other languages, it is relatively easy to understand this piece of knowledge. For example, from the following two writing methods, we can see that there are so many commonalities between the language features of different languages.
Es6: (attachment: the theme of this article is python, so it is only a brief introduction to the definition of classes and the creation of instances in js, in order to illustrate the similarity of writing)
ClassPerson {constructor (name, age) {this.name = name this.age = age}} const child1 = newPerson ('Xiao Ming',10)
Python: (the core points are written in the notes)
# define a Person class: many child instances classPerson (object) can be created according to the Person class: address = 'Earth'# class properties (instance public) def _ _ init__ (self, name, age): # when creating an instance, the _ _ init__ () method is automatically called self.name = name self.age = age def get_age (self): # defines the instance method, and its first parameter is always self Point to the instance that called the method, and the other parameters are the same as the ordinary function: returnself.agechild1 = Person ('Xiao Ming',10) child2 = Person (' Xiao Hong',9) print child1.name # 'Xiao Ming'print child2.get_age () # 9print child1.address #' Earth'print child2.address # 'Earth' inheritance
Child belongs to the Student class, and the Student class belongs to the People class, which leads to inheritance: you can add your own method properties after you get the method properties of the parent class.
There is no one to answer the question? The editor has created a Python learning exchange QQ group: 857662006 look for like-minded partners to help each other, and there are also good video learning tutorials and PDF e-books in the group! ClassPerson (object): def _ init__ (self, name, age): self.name = name self.age = ageclassStudent (Person): def _ init__ (self, name, age, grade): super (Student,self). _ init__ (name, age) # Person.__init__ (self, name, age) self.grade = grades = Student ('Xiao Ming',10,90) print s.name #' Xiao Ming'print s.grade # 90
You can see that the subclass adds the grade attribute to the parent class. We can look at the type of s again.
Isinstance (sforce person) isinstance (sdepartment Student)
As you can see, on an inheritance chain in Python, an instance can be seen as either its own type or its parent class.
This is the end of the content of "what are the similarities between Python and JS"? thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.