In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "how to understand the control structure of Python". 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!
01 for cycle
For loop is one of the most basic control structures of Python. A common pattern for using for loops is to use the range function to generate a range of values and then iterate over them.
Res = range (3) print (list (res)) # output: [0,1,2] for i in range (3): print (I)''output: 0 12''
For Loop list
Another common pattern for using for loops is to iterate over lists.
Martial_arts = ["Sambo", "Muay Thai", "BJJ"] for martial_art in martial_arts: print (f "{martial_art} has influenced\ modern mixed martial arts")''output: Sambo has influenced modern mixed martial arts Muay Thai has influenced modern mixed martial arts BJJ has influenced modern mixed martial arts''02 while loop
A while loop is a loop that is repeated when the condition is valid. A common use of while loops is to create infinite loops. In this example, the while loop is used to filter the function, which returns one of two types of attack.
Def attacks (): list_of_attacks = ["lower_body", "lower_body", "upper_body"] print ("There are a total of {lenlist_of_attacks)}\ attacks coming!") For attack in list_of_ attacks: yield attack attack = attacks () count = 0 while next (attack) = = "lower_body": count + = 1 print (f "crossing legs to prevent attack # {count}") else: count + = 1 print (f "This is not lower body attack,\ I will cross my arms for# count}")''output: There are a total of 3 attacks coming! Crossing legs to prevent attack # 1 crossing legs to prevent attack # 2 This is not a lower body attack, I will cross my arms for # 3''03 if/else statement
The if/else statement is a common statement that branches between judgments. In this example, if/elif is used to match branches. If there is no match, the last else statement is executed.
Def recommended_attack (position): "" Recommends an attack based on the position "if position = =" full_guard ": print (f" Try an armbar attack ") elif position = =" half_guard ": print (f" Try a kimura attack ") elif position = =" fu1l_mount ": print (f" Try an arm triangle ") else: print (f" You're on your own \ there is no suggestion for an attack ") recommended_attack (" full_guard ") # output: Try an armbar attackrecommended_attack (" z_guard ") # output: You're on your own, there is no suggestion for an attack04 generator expression
Generator expressions are based on the concept of yield statements, which allow lazy evaluation of sequences. The benefit of the generator expression is that nothing is evaluated or put into memory until it is actually evaluated. This is why the following example can be performed in a generated sequence of infinite random attacks.
In the generator pipeline, lowercase attacks such as "arm_triangle" are converted to "ARM_TRIANGLE", and then the underscore is removed to get "ARM TRIANGLE".
Def lazy_return_random_attacks (): "" Yield attacks each time "import random attacks = {" kimura ":" upper_body "," straight_ankle_lock ":" lower_body "," arm_triangle ":" upper_body "," keylock ":" upper_body " "knee_bar": "lower_body"} while True: random_attack random.choices (list (attacks.keys () yield random attack # Make all attacks appear as Upper Case upper_case_attacks =\ (attack.pop (). Upper () for attack in\ lazy_return_random_attacks ()) next (upper-case_attacks) # output: ARM- TRIANGLE## Generator Pipeline: One expression chains into the next # Make all attacks appear as Upper Case upper-case_attacks =\ (attack. Pop (). Upper () for attack in\ lazy_return_random_attacks () # remove the underscore remove underscore =\ (attack.split ("_") for attack in\ upper-case_attacks) # create a new phrase new_attack_phrase =\ (".join (phrase) for phrase in\ remove_underscore) next (new_attack_phrase) # output: 'STRAIGHT ANKLE LOCK'for number in range (10): print (next (new_attack_phrase)) 'output: KIMURA KEYLOCK STRAIGHT ANKLE LOCK''05 list derivation
Syntactically, list deduction is similar to generator expressions, but if you compare them directly, you will find that list deduction is evaluated in memory. In addition, the list derivation is optimized C code, which can be considered a significant improvement on the traditional for loop.
Martial_arts = ["Sambo", "Muay Thai", "BJJ"] new_phrases [f "mixed Martial Arts is influenced by\ (martial_art)" for martial_art in martial_arts] print (new_phrases) ['Mixed Martial Arts is influenced by Sambo',\' Mixed Martial Arts is influenced by Muay Thai',\ 'Mixed Martial Arts is influenced by BJJ'] 06 Intermediate topic
With this basics in place, it is important to understand not only how to create code, but also how to create maintainable code. One way to create maintainable code is to create a library, and the other is to use code written by installed third-party libraries. The overall idea is to minimize and decompose complexity.
Use Python to write libraries
It is important to use Python to write a library, and it does not take a long time to import the library into the project. The following examples are the basics of writing a library: there is a folder called funclib in the repository with a _ init_ .py file. To create a library, you need to have a module that contains functions in this directory.
First create a file.
Touch funclib/funcmod.py
Then create a function in the file.
"This is a simple module" def list_of_belts_in_bjj (): "Returns a list of the belts in Brazilian jiu-jitsu"belts= [" white "," blue "," purple "," brown "," black "] return beltsimport sys;sys.path.append (".. ") From funclib import funcmod funcmod.list_of_belts_in-bjj () # output: ['white',' blue', 'purple',' brown', 'black']
Import library
If the library is the directory above, you can use the Jupyter add sys.path.append method to import the library. Next, import the module using the namespace of the folder / file name / function name you created earlier.
Install third-party libraries
Third-party libraries can be installed using the pip install command. Note that the conda command (
Https://conda.io/docs/user-guide/tasks/manage-pkgs.html) is an optional alternative to the pip command. If you use the conda command, the pip command will also work well, because pip is a replacement for the virtualenv virtual environment, but it can also install software packages directly.
Install the pandas package.
Pip install pandas
Alternatively, you can use the requirements.txt file to install the package.
> ca requirements.txt pylint pytest pytest-cov click jupyter nbval > pip install-r requirements.txt
The following is an example of using a small library in Jupyter Notebook. It's worth pointing out that it's easy to create giant cobwebs of program code in Jupyter Notebook, and the very simple solution is to create some libraries, then test and import them.
"This is a simple module" import pandas as pd def list_of_belts_in_bjj (): "Returns a list of the belts in Brazilian jiu-jitsu"belts = [" white "," blue "," purple "," brown " "black"] return belts def count_belts (): "Uses Pandas to count number of belts" belts = list_of_belts_in_bjj () df = pd.Dataframe (belts) res = df.count () count = res.values.tolist () [0] return countfrom funclib.funcmod import count_beltsprint (count_belts ()) # output: 5
Class
Classes can be reused and interacted with in Jupyter Notebook. The simplest class type is a name, and the class is defined as follows.
Class Competitor: pass
This class can be instantiated as multiple objects.
Class Competitor: passconor = Competitor () conor.name = "Conor McGregor" conor.age = 29 conor.weight = 155nate = Competitor () nate.name = "Nate Diaz" nate.age = 30 nate.weight = 170def print_competitor_age (object): "" Print out age statistics about a competitor "" print (f "{object.name} is {object.age} years old") print_competitor_age (nate) # output: Nate Diaz is 30 years oldprint_competitor_age (conor) # output: Conor McGregor is 29 years old
The difference between classes and functions
The main differences between classes and functions include:
Functions are easier to explain.
A function (typically) has a state only inside the function, while the class maintains an immutable state outside the function.
Classes can provide a higher level of abstraction at the expense of complexity.
This is the end of "how to understand the Control structure of Python". Thank you for your 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.