Python learning from the entry operation List

Source: Internet
Author: User
This article describes how to learn Python from the entry operation List. it has some reference value. For more information, see section 4.1 traversing the entire list.

We often need to traverse all the elements in the list and perform the same operation on each list. This is useful and repetitive during repetitive work. For example, in a game, you may need to translate each interface element to the same distance. For a list containing numbers, you may need to perform the same statistical operation on each element. on the website, you may need to display each title in Article 3. To perform the same operation on each element in the list, you can use the for loop in Python.

If we have a magician list, we need to print out the names of each magician. Therefore, we can obtain each name in the list separately, but this will cause many problems. For example, if the list is too long, it will contain a large number of repeated code. In addition, the code must be modified whenever the length in the list changes. By using the for loop, Python can solve these problems.

The following uses a for loop to print all names in the magician list:

Magicians = ["alice", "david", "carolina"] for magician in magicians :( magician) running result: alicedavidcarolina first, we define a list as in chapter 3. Next, we define a for loop. this line of code allows Python to remove a name from the list magicians and store it in magician. Finally, let Python print the name stored in the variable magician. In this way, Python will repeat every name in the list. We can interpret the code like this: for every magician in the magician list, print out its name. The output is very simple, that is, all the names in the list: 4.1.1 it is very important to thoroughly study the concept of loop, especially when the operation is repetitive, the use of automatic loop will increase a lot of efficiency, it is also one of the common ways for computers to automatically repeat their work. For example, in the previous magicians. in the simple loop used in py, Python will first read the first line of code: for magician in magicians: This line of code, let Python obtain the first value ("alice") in magicians in the list and store it in the variable magician. Next, Python reads the next line of code. Print (magician), which enables Python to print the value of magician-still "alice ". Since the list also contains other values, Python returns the first line of the loop: for magician in magicians: python gets the next name in the list -- "david ", and store it in the variable magician. execute the following code: print (magician) Python re-prints the value of the variable magician "david ". Next, Python executes the entire loop again to process the last value in the list-"Lina. So far, there are no other values in the list, so Python then executes the next line of code of the program. In this instance, there is no other code behind the for loop, so the program ends. When you start to use a loop, keep in mind that each element in the list will undergo a repeating step, regardless of the number of elements in the list. If the list contains 1 million elements, Python repeats the execution for 1 million times, and the speed is usually very fast. In addition, when writing a for loop, you can specify any name for the temporary variables used to store each value in the list. However, it is helpful to select a meaningful name that describes a single list element. For example, for the kitten list, puppy list, and general list, writing the first line of code for the for loop as follows is a good choice: for dog in dogs: for cat in cats: for item in _ of_items: these naming conventions help us understand the operations that will be performed on each element in the for loop. The singular and plural names help us determine whether the code processes a single list element or the entire list. 4.1.2 execute more operations in the for loop. you can perform any operations on each element in the for loop.
Magicians = ["alice", "david", "carolina"] for magician in magicians: print (magician. title () + ", that was a greet trick! ") The output below shows that each magician in the list prints a personalized message: Alice, that was a greet trick! David, that was a greet trick! Carolina, that was a greet trick! How many lines of code can be included in the for loop. After the code line for magician in magicians, each indented code line is a part of a loop and will be executed once for each value in the list. Therefore, you can perform any number of operations on each value in the list. Next we will add a line of code to tell each magician that we are looking forward to his next performance:
Magicians = ["alice", "david", "carolina"] for magician in magicians: print (magician. title () + ", that was a greet trick! ") Print (" I can't wait to see your trick, "+ magician. title () + ". \ n ") because both print statements are indented, they will be executed once for each magician in the list. The linefeed "\ n" in the second print statement inserts an empty line after each iteration, so as to neatly group the messages for magicians: Alice, that was a greet trick! I can't wait to see your next trick, Alice. David, that was a greet trick! I can't wait to see your next trick, David. mongolina, that was a greet trick! I can't wait to see your next trick, please Lina! How many lines of code can be included in the for loop. In fact, we will find it useful to use the for loop to execute many different operations on each element. 4.1.3 What should I do after the for loop ends? Generally, we need to propose other tasks that must be completed by summative output or subsequent execution of the program. After a for loop, code without indentation is executed only once, instead of repeating. Below is a message to thank all the magicians for their wonderful performances. If you want to print a thank-you message to all magicians after the message is printed, you need to put the corresponding code behind the for loop without indent:
Magicians = ["alice", "david", "carolina"] for magician in magicians: print (magician. title () + ", that was a great trick! ") Print (" I can't wait to see your next trick, "+ magician. title () + ". \ n ") print (" Thank you, everyone. that was a great magic show! ") As we can see above, the first two print statements are executed repeatedly for each magician in the list. However, since the third print statement is not indented, it is only executed once: Alice, that was a great trick! I can't wait to see your next trick, Alice. David, that was a great trick! I can't wait to see your next trick, David. mongolina, that was a great trick! I can't wait to see your next trick, please Lina. Thank you, everyone. That was a great magic show! Using the for loop to process data is a good way to perform the overall operation. For example, you may use a for loop to initialize the game-traverse the role list and display each role on the screen. Then, add a non-indent code block after the loop, draw all roles on the screen and display a play Now. 4.2 avoid indentation errors Python uses indentation to determine the relationship between the code line and the previous code line. In the previous example, the code lines that show messages to magicians are part of the for loop because they are indented. Python makes the code easier to read through indentation. In short, it requires us to use indentation to make the code clean and clear. In a long Python program, we will see code blocks with different indentation levels, which gives us a general understanding of the organizational structure of our team program. When writing code that must be correctly indented, pay attention to some common indentation errors. For example, sometimes programmers indent code blocks that do not need to be indented, but forget to indent code blocks that must be indented. By viewing such error examples, we can avoid them and fix them when they appear in the program. 4.2.1 do not indent the code lines that are located behind and are part of a loop. If we forget to indent, Python will remind you:
Magicians = ["alice", "david", "carolina"] for magician in magicians: print (magician. title () + ", that was a great trick! ") The print statement should be indented but not indented. When Python does not find the code block to be indented, it will let us know that there is a problem with the code line. "/Home/zhuzhu/title4/magicians. py", line 3 print (magician. title () + ", that was a great trick! ") ^ IndentationError: expected an indented block indicates that our code is not indented and should be indented as expected. Generally, the line of code that follows the for statement is indented to eliminate this indentation error. 4.2.2 forget to indent additional code lines
magicians = ["alice","david","carolina"]for magician in magicians:print(magician.title() + ", that was a great trick!")print("I can't wait to see your next trick, " + magician.title() + ".\n" )
Magicians = ["alice", "david", "carolina"] for magician in magicians: print (magician. title () + ", that was a great trick! ") Print (" I can't wait to see your next trick, "+ magician. title () + ". \ n ") print (" Thank you, everyone. that was a great magic show! ") Because the third print code line is indented, it will execute Alice, that was a great trick for each magician in the list! I can't wait to see your next trick, Alice. Thank you, everyone. That was a great magic show! David, that was a great trick! I can't wait to see your next trick, David. Thank you, everyone. That was a great magic show! Carolina, that was a great trick! I can't wait to see your next trick, please Lina. Thank you, everyone. That was a great magic show! This is also a logical error, similar to the error in section 4.2.2. Python does not know your intention. as long as the code conforms to the syntax, it will run. If only one operation is performed multiple times, check whether the code for this operation should not be indented. 4.2.5 The colon is missing: the for statement tells Python at the end that the next row is the first row of the loop.
Magicians = ["alice", "david", "carolina"] for magician in magiciansprint (magician. title () + ", that was a great trick! ") Run: File"/home/zhuzhu/title4/magicians. py ", line 2 for magician in magicians ^ SyntaxError: invalid syntax (the syntax is invalid) if we accidentally omit the colon, it will result in an invalid syntax prompt, because Python does not know what we want. Although this error is easy to eliminate, it is not so easy to discover. It takes a lot of time to find such a single-character error. This error is hard to find because it is often unexpected. Practice
The running result is as follows:
Animals = ["lion", "tiger", "wolf", "leopard"] for animal in animals: print (animal. title () + "s are good at hunting. ") print (" Any of these animals like eating meat! ") First define an animal list, and use the for loop to traverse each animal in the list. The first print prints a common animal and belongs to the for loop; the second print is outside the for loop. when the for loop is run, it is a summative language, so it will only print once: Lions are good at hunting. tigers are good at hunting. wolfs are good at hunting. leopards are good at hunting. any of these animals like eating meat! 4.3 there are many reasons to store a set of numbers for creating a value list. for example, in a game, you need to track the positions of each role and the maximum score of players. In data visualization, almost all data is processed as a collection of numbers (such as temperature, distance, population quantity, longitude, and latitude. The list is ideal for storing digital sets, and Python provides many tools to help us process the list of numbers. After understanding how to use these tools effectively, even if it contains millions of elements, the code we write can run well. 4.3.1 ()
For value in range (12345): print (value), the output starts from 1 to 5 and ends: when the range () function is used, if the output is not as expected, add the specified value to 1 or minus 1.4.3.2 and use the range () function to create a number list.
Numbers = list (range () print (numbers) results: [1, 2, 3, 4, 5] When using the range () function, you can also specify the step size. For example, the following code prints 1 ~ Odd number in 10:
Numbers = list (range (, 2) print (numbers) in this instance, the function range () starts from 2, and then continuously adds 2, until it reaches or exceeds the end value (10), the output result is as follows: [1, 3, 5, 7, 9] using the range () function can almost create any desired number set, for example, how to create a list containing the first 10 (1 ~ 10) What about the square? In Python, two asterisks (**) represent multiplication operations. The following code demonstrates how to add the square of the first 10 integers to a list:
Squares = [] for num in range (1, 11): square = num ** 2 squares. append (square) print (squares) first, an empty list is created. Next, use the range () function to traverse Python through 1 ~ Value of 10. In a loop, calculate the square of the current value, store the result to the square variable, and then append the calculated square value to the end of the squares list. Finally, when the loop ends, print the list squares [1, 4, 9, 16, 25, 36, 49, 64, 81,100] to create a more complex list, you can use either of the above two methods. Sometimes, using temporary variables makes the code easier to read. In other cases, this will only make the code become longer without any concern. We should consider writing code that is clear and easy to understand and can complete the required functions; when coding, we should consider adopting a more efficient method.
Squares = [value ** 2 for value in range ()] print (squares) to use this syntax, first specify a descriptive list name, such as squares; specify a left square brackets and define a pair to generate the values in the list you want to store. In this example, the expression is value ** 2, which calculates the square value. Next, write a for loop to provide a value for the expression, and add the right square brackets. In this instance, the for loop is for value in range (), and the value is 1 ~ 10 is provided to the expression value ** 2. Note that there is no colon at the end of the for statement. The result is the same as the number of shards list we saw earlier: [1, 4, 9, 16, 25, 36, 49, 64, 81,100] to create your own list resolution, some exercises are required, but after you are proficient in creating a regular list, you will find that this is completely worthwhile. When writing three or four lines of code to generate a list is complicated, you should consider creating a list resolution. In fact, I like list parsing very much. this method is too easy, and you don't need to define a list. you just need to write the statements in parentheses, which is easy and convenient, try this method to create a short number list representation. Try it 4-3 to 20: Use a for loop to print the number 1 ~ 20 (inclusive); 4-4 1 million: Create a list containing numbers 1-4 ~ 1000000. print the numbers in a for loop (if the output time is too long, press Ctrl + C to stop the output or close the output window ). 4-5 computing 1 ~ Sum of 1000000: Create a list containing numbers 1 ~ 1000000. use the min () and max () functions to verify that the list does start from 1 and end from 1000000. In addition, call the sum () function for this list to see how long it takes for Python to add 1 million numbers. 4-6 odd: specify the third parameter for the range () function to create a list, which contains 1 ~ An odd number of 20. print all these numbers in a for loop. a multiple of 4-7 3: Create a list, which contains 3 ~ A number that can be divisible by 3 in 30; the number in the list is printed out using a for loop; 4-8 Cube: The same number is multiplied into a cube three times. For example, in Python, the cube of 2 is represented by 2 ** 3. Create a list containing the first 10 integers (1 ~ 10) The cubes are printed out using a for loop. 4-9 cubes are parsed to generate a list containing the first 10 integers. Analysis: The questions in this section mainly show how to use the for loop, including min () function, max () function, and sum () function. Try List resolution more, I think this is really a good method. we only need to generate the list we need in one step. remember the difference between the range () function. the list () function generates the list. To operate the number list. 4-3: This article describes how to use the for loop, and the difference between the range () function for num in range (): print (num) 4-4: this article exercises our usage of the for loop and the difference between the range () function, but I want to tell you that Python can handle a large number, not simply a small number in the book.
For num in range (bytes 01): When print (num) is run, traverse 1 ~ 1000000 still takes more than 10 seconds. remember the difference, which is 4-5 better than what we want: Use the list () function to create a list, then verify the maximum and minimum values and sum the numbers.
numbers =
Numbers = [] # create an empty list to store the generated list number for num in range (): number = num * 3 numbers. append (number) print (numbers) digits = [value * 3 for value in range (1, 11)] print (digits)
The first method is to generate a list. First, we define an empty list, and then define a loop to add the values generated each time to the end of the empty list, finally, we need to generate the list. The second method is to use list parsing. we can see that we only need one statement to generate a number list, as long as we know the expression of the list. 4-8: This question is similar to the previous one, but the list expression method is different. the solution is the same.
Numbers = [] # create an empty list to store the generated list number for num in range (1, 11): number = num ** 3 numbers. append (number) print (numbers) digits = [value ** 3 for value in range (1, 11)] print (digits)
We can see that we only modified the expression of the list. when solving the problem, we first thought about how to solve the problem. after thinking about it, we should compile the code. First, we should generate a list, this list contains 1 ~ 10 cubes, then we need to convert Mr To 1 ~ In this case, we use the range () function, and then add the changes to the generated number to a list, you only need to add it to the new list after each generation. 4.4 use part of the list in Chapter 3, we learned how to access a single list element. In this chapter, we have been learning how to process all the elements in the list. We can also process part of the list, which is called slice in Python. 4.4.1 to create a slice, you can specify the index of the first element and the last element to be used. Like the range () function, Python stops when it reaches the element before the second index we specify. To output the first three elements in the list, you need to specify the index 0 ~ 3, which outputs the elements 0, 1, and 2 respectively. The following example deals with a list of sports players: players. pyplayers = ["charles", "martina", 'Michael ', 'Florence', 'Lily'] print (players [0: 3]): a piece of the code print list, it only contains the top three players. The output is also a list containing the top three players: ['chars', 'Martina ', 'Michael']. we can generate any subset of the list, for example, if we want to extract the 2nd ~ Four elements: you can set the starting index to 1 and define the ending index as 4: players = ["charles", "martina", 'Michael ', 'Florence ', 'Lil'] print (players []) this time, the slice starts with "martina" and finally "florence": ['Martina ', 'Michael ', 'Florence '] if the first index is not set, Python will automatically start from the beginning of the list: players = ["charles", "martina", 'Michael', 'Florence ', 'Lil'] print (players [: 4]) because no starting index is specified, Python extracts from the beginning of the list: ['chars', 'Martina ', 'Michael ', 'Florence '] Similar syntax can be used to terminate a slice at the end of the list. For example, if you want to extract all elements from the first element to the end of the list, you can set the starting index to 2 and omit the ending index: players = ["charles", "martina ", 'Michael ', 'Florence', 'Eli '] print (players [2:]) Python returns all elements from the first element to the end: ['Michael ', 'Florence ', 'Lil'] regardless of the length of the list, this syntax allows us to output all elements from a specific position to the end of the list. As mentioned earlier in this book, negative index returns the elements at the corresponding distance from the end of the list, so we can output any slices at the end of the list. For example, if we want to output the last three players in the list, we can use slice players [-3:] players = ["charles", "martina", 'Michael ', 'Florence ', 'Lil'] print (players [-3:]) The above code prints the names of the last three players, even if the length of the player list changes. 4.4.2 traverse slice if you want to traverse some elements of the list, you can use slice in the for loop. In the following example, we traverse the top three players and print their names: players = ["charles", "martina", 'Michael ', 'Florence ', 'Lil'] # thired_players = players [: 3] # print (thired_players print ("Here are the first three players on my team:") for player in players [0: 3]: the print (player) code does not traverse the entire list of players, but only traverses the top three players: Here are the first three players on my team: charles martina michael, in many cases, slice is useful. For example, when writing a game, we can add the final score to a list when the player exits the game. Then, to obtain the highest score of the player, we can sort the list in descending order and create a slice that contains only the first three scores. When processing data, you can use slice for batch processing. when writing a Web application, you can use slice to display information by Page and display the appropriate quantity of information on each page. The slicing function is really useful. we need to use the first three items in a list and the last three items in a list. we may use sorted () when using slicing () functions are used to process slice. these are all part of the slice, the original list, and the purpose of slice, when we need to use a part of the original slice, we will use the slice function. 4.4.3 copying a list we often need to create a new list based on the existing list. Next we will introduce the working principle of list replication and a situation where the copy list can be of great help. To copy the list, you can create a slice that contains the entire list by omitting the starting index and terminating the index ([:]) at the same time. This allows Python to create a slice that begins with the first element and ends with the last element, that is, copying the entire list. Suppose there is a list containing four of our favorite foods, and we want to create another list containing all the foods that a friend liked. However, this friend liked our favorite food, so we can create this list by copying it: foods. py my_foods = ["pizza", 'nostart', 'falafel'] friend_foods = my_foods [:] print ("My favorite foods are:") print (my_foods) print ("\ nMy friend's favorite foods are:") print (friend_foods)
We first created a list named my_foods, and then a new list named friend_foods. We extract a slice from the list my_foods without creating any indexes, create a copy of the list, and store the copy to the variable friend_foods. After printing each list, we found that they contain the same foods: My favorite foods are: ['pizza', 'nota', 'falafel'] My friend's favorite foods are: ['pizza', 'notes', 'falafel'] to verify that we actually have two lists, the following adds a food in each list, verify that every list contains any favorite foods: my_foods = ["pizza", 'nota', 'falafel'] friend_foods = my_foods [:] my_foods.append ("cannoli ") friend_foods.append ("ice cream") print ("My favorite foods are:") print (my_foods) print ("\ nMy friend's favorite foods are:") print (friend_foods)
As in the previous example, we first copy the elements of my_foods to the new list of friend_foods. Next, add a type of food to each list: add "cannno" to my_foods, and add "ice cream" to friend_foods ". Finally, print the two lists to verify that these two foods are included in the correct list. My favorite foods are: ['pizza', 'notes', 'falafel', 'cannolil'] My friend's favorite foods are: ['pizza', 'nozza ', 'falafel', 'Ice Cream'] the output indicates that "cannoli" is included in your favorite food list, but "ice cream" is not. "Ice cream" is included in your friend's favorite food list, but "cannoli" is not. If we simply assign my_foods to friend_foods, we cannot get two lists. For example, the following example shows how to copy a list without using slices: my_foods = ["pizza", 'nota ', 'falafel'] # This does not work. friend_foods = my_foods my_foods.append ("cannoli") friend_foods.append ("ice cream") print ("My favorite foods are:") print) print ("\ nMy friend's favorite foods are:") print (friend_foods) grant my_foods to friend_foods instead of storing copies of my_foods to friend_foods. this syntax allows Python to associate the new variable friend_foods with the list contained in my_foods. Therefore, both variables point to the same list. Because of this, when we add "cannoli" to my_foods, it will also appear in friend_foodsz; similarly, although "ice cream" seems to be added only to friend_foods, but it will also appear in the two lists. The output indicates that the two lists are the same. this is not the expected result: My favorite foods are: ['pizza', 'notes', 'falafel', 'cannolil ', 'Ice Cream'] My friend's favorite foods are: ['pizza', 'notes', 'falafel', 'cannolil ', 'Ice Cream'] The following is an analysis of this situation, because I do not quite understand this situation, but after learning this situation, I learned about the principle of storage elements in Python and how to open up space: [object Object]

When the value assignment method is used to generate friend_foods, my_foods and friend_foods Share a memory. in Python, no new memory is opened, as shown in, so when we assign values, it will look like the following:

TypeError: 'tuple' object does not support item assignment

The running result shows that when we try to modify the element of the tuples, an error occurs, prompting us that we cannot modify the values of the tuples.

Cafeterias = ("rice", "nozza", "porridge", "hamburger", "pizza") print ("Original menu:") for cafeteria in cafeterias: print (cafeteria) # cafeterias [-1] = "dami" cafeterias = ("pizza", 'hamburgger', 'Rice ', 'milk', 'drumstick') print ("\ nModified menu: ") for cafeteria in cafeterias: print (cafeteria) run the following results: Original menu: Invalid menu: pizzahamburgerricemilkDrumsticks. the running results show that although we do not You can modify the values of elements in a tuples, but you can assign values to them as a whole. this is allowed. Therefore, you can assign values to tuples again. this is allowed and legal, the system does not report errors. 4.6 setting the code format as the program we write grows, it is necessary to understand some code format settings conventions. Please take the time to make our code easy to read; make the code easy to read to help us understand what the program is doing, or help others understand the code we have written. To ensure that the structure of the code written by everyone is roughly the same, Python programmers follow some format settings conventions. After learning to write clean Python, you can understand the overall structure of the Python code written by others-as long as they follow the same guide as you. Professional programmers should follow these guidelines from now on to develop good habits. 4.6.1 to propose Python language modification suggestions, you need to write Python improvement proposals (Python Enhancement Proposal, PEP ). PEP8 is one of the oldest PEP and provides a guide to code format setting for Python programmers. PEP8 is very long, but mostly related to complicated encoding structures. The authors of the Python format setting guide know that the code is read more times than written. After the code is compiled, you need to read it during debugging; when adding new functions to the program, it takes a long time to read the code; when sharing the code with other programmers, these programmers will also read them. If you must make a choice between easy coding and easy reading, Python programmers almost always choose the latter. The following guidelines help us to write clear code from the very beginning. 4.6.2 indent PEP 8 it is recommended that four spaces be used for each level of indentation to improve readability and leave sufficient multi-level indentation space. In word processing documents, tabs rather than spaces are often used for indentation. This works well for word processing documents, but the mixed use of tabs and spaces can confuse the Python interpreter. Each text provides a setting to convert the input tab to a specified number of spaces. We should use the Tab key when writing code, but we must set the editor so that it can insert spaces instead of tabs in the document. Mixing tabs and spaces in the program may cause extremely difficult problems. If both tabs and spaces are used, all tabs in the file can be converted to spaces. most editors provide this function. 4.6.3 many Python programmers recommend that each line contain no more than 80 characters. When such a guide was initially developed, in most computers, each line of the terminal window can only accommodate 79 characters; currently, each line of the computer screen can accommodate a large number of characters, why should we use the 79-character standard president? There are other reasons. Professional programmers usually open multiple files on the same screen. Using the standard President, we can open two or three files on the screen side by side to see the entire line of each file at the same time. PEP 8 also recommends that the president should not exceed 72 characters, because some tools will add formatting characters at the beginning of each line of comment when automatically generating documents for large projects. In PEP 8, the guide to the president is not an insurmountable red line, and some groups set the maximum President to 99 characters. We don't have to worry too much about the long term of the code during our study, but don't forget to write programs in collaboration. almost everyone follows the PEP 8 Guide. In most editors, you can set a visual flag-usually a vertical line, allowing you to know where the line cannot be crossed. 4.6.4 empty lines can be used to separate different parts of the program. We should use empty lines to organize program files, but we should not abuse them. as long as we do as shown in the example in this book, we can grasp the balance. For example, if we have five lines of code to create a list and three lines of code to process the list, it is appropriate to separate the two parts with a blank line. However, we should not use three or four blank lines to separate them. Empty lines do not affect code execution, but affect code readability. The Python interpreter interprets the code based on horizontal indentation, but does not care about vertical spacing.

Original menu:
Rice
Notify
Porridge
Hamburger
Pizza
Modified menu:
Pizza
Hamburger
Rice
Milk
Drumsticks

The above is the details of Python from the entry operation List. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.