当前位置:网站首页>4-operation list (loop structure)

4-operation list (loop structure)

2022-06-24 07:55:00 axinawang

4.1 Traverse the entire list

When you need to do the same for each element in the list , You can use Python Medium for loop .

Use for Loop to print all the names in the magician list :

magicians = ['alice', 'david', 'carolina'] 
for magician in magicians:
    print(magician)

4.1.1 Elaborate on the cycle process

Use singular and plural names , It can help you determine whether the code segment deals with a single list element or the whole list .

4.1.2 stay for Do more in the loop

magicians = ['alice', 'david', 'carolina'] 
for magician in magicians: 
    print(f"{magician.title()}, that was a great trick!")
    print(f"I can't wait to see your next trick, {magician.title()}.\n")

4.1.3 stay for Do something at the end of the loop

for What to do when the cycle is over ? Usually , You need to provide summary output or follow up with other tasks that the program must complete .

magicians = ['alice', 'david', 'carolina'] 
for magician in magicians: 
    print(f"{magician.title()}, that was a great trick!")
    print(f"I can't wait to see your next trick, {magician.title()}.\n")
    
print("Thank you, everyone. That was a great magic show!")

4.2 Avoid indenting errors

Python Determine the relationship between a line of code and the previous line based on indentation .

4.2.1 Forget to indent

Python When you don't find a block of code that you want to indent , Will let you know which line of code is wrong .

 File "E:\...\magicians.py", line 3
    print(f"{magician.title()}, that was a great trick!")
    ^
IndentationError: expected an indented block after 'for' statement on line 2

Usually , Will follow closely for The line after the statement is indented , This kind of indentation error can be eliminated . 

4.2.2 Forget to indent extra lines of code

for magician in magicians: 
    print(f"{magician.title()}, that was a great trick!")
print(f"I can't wait to see your next trick, {magician.title()}.\n")

Grammatically , these Python The code is legal , But because of a logic error , The result is not as expected .

4.2.3 Unnecessary indentation

magicians = ['alice', 'david', 'carolina'] 
    for magician in magicians: 
    print(f"{magician.title()}, that was a great trick!")
    print(f"I can't wait to see your next trick, {magician.title()}.\n")
File "E:\...\magicians.py", line 2
    for magician in magicians: 
IndentationError: unexpected indent

4.2.4 Unnecessary indentation after loop

If you accidentally indent the code that should be executed after the loop ends , The code will be repeated for each list element . In some cases , This can lead to Python Report grammatical errors , But in most cases , This only leads to logical errors .

4.2.5 Missing colon

for The colon at the end of a statement tells Python, The next line is the first line of the loop .

If you omit a colon , as follows :

magicians = ['alice', 'david', 'carolina'] 
for magician in magicians
    print(f"{magician.title()}, that was a great trick!")
File "E:\...\magicians.py", line 2
    for magician in magicians
                             ^
SyntaxError: expected ':'

Give it a try

practice 4-1: Pisa

Think of at least three kinds of pizza you like , Store its name in a list , Reuse for Loop to print out the name of each pizza . Amend this for loop , Make it print a sentence containing the name of the pizza , Not just the name of pizza . For each pizza , All display one line of output , Here is an example .I like pepperoni pizza. Add a line of code to the end of the program , It's not in for In circulation , Point out how much you like pizza . The output should contain messages for each pizza , There is also a concluding sentence , Here is an example .I really love pizza!

practice 4-2: animal

Think of at least three animals with common characteristics , Store its name in a list , Reuse for Cycle to print out the name of each animal . Modify this program , Make it print a sentence for each animal , Here is an example .A dog would make a great pet. Add a line of code to the end of the program , Point out what these animals have in common , Print the following sentences .Any of these animals would make a great pet!

4.3 Create a list of values

4.3.1 Using functions range()

function range() Give Way Python Starting from the first value specified , And stop when you reach the second value you specify .

for number in range(1,5):
	print(number)

Call function range() when , You can also specify only one parameter , So it will start from 0 Start . for example ,range(6) Return number 0~5. 

4.3.2 Use range() Create a list of numbers

To create a list of numbers , You can use functions list() take range() The results are converted directly to a list .

numbers = list(range(1, 6))
print(numbers)

Using functions range() when , You can also pass in a third parameter as the step size .

even_numbers = list(range(2, 11, 2)) 
print(even_numbers)

Using functions range() You can create almost any set of numbers you need . for example , How to create a list , Including before 10 It's an integer (1~10) What about the square of ?

squares=[]
for value in range(1,11):
	square=value ** 2
	squares.append(square)
print(squares)

You can use no temporary variables  

squares=[]
for value in range(1,11):
	squares.append(value ** 2)
print(squares)

Saving 20ms.

occasionally , Using temporary variables makes the code easier to read ; And in other cases , Doing so will only make the code unnecessarily longer , It takes a long time to execute . The first thing you should consider is , Write code that is clear and easy to understand and can complete the required functions , Wait until you review the code , Then consider a more efficient approach .

4.3.3 Perform simple statistical calculations on a list of numbers

There are several dedicated to dealing with lists of numbers Python function . for example , You can easily find the maximum of the number list 、 The sum of the minimum and the sum :

max( list ),min( list ),sum( list )

4.3.4 List of analytical

List parsing will for The loop and the code that creates the new element merge into a single line , And automatically attach new elements .

The following example uses list parsing to create the square list you saw earlier :

squares = [value**2 for value in range(1, 11)]
print(squares)

Give it a try

practice 4-3: Count to 20

Use one for Number of cycles 1~20( contain ).

practice 4-4: One million

Create a containing number 1~1 000 000 A list of , Use one more for Loop to print these numbers .( If the output time is too long , Press Ctrl + C Stop output or close the output window .)

practice 4-5: Sum a million

Create a containing number 1~1 000 000 A list of , Reuse min() and max() Verify that the list is from 1 Start 、 To 1 000 000 The end of the . in addition , Call the function on this list sum(), have a look Python How long does it take to add a million numbers . practice

4-6: Odd number

By giving the function range() Specify the third parameter to create a list , It includes 1~20 The odd number , Use one more for Loop to print these numbers .

practice 4-7:3 Multiple

Create a list , It includes 3~30 Can be 3 Divisible number , Use one more for Loop to print the numbers in this list .

practice 4-8: cube

Multiplying the same number three times is called cubic . for example , stay Python in ,2 Cube for 2**3 Express . Please create a list , Including before 10 It's an integer (1~10) The cube of , Use one more for Loop to print out these cubes .

practice 4-9: Cubic analysis Use list parsing to generate a list , Including before 10 The cube of an integer .

4.4 Use part of the list

4.4.1 section

Some elements of the list are called slices .

To create slices , You can specify the index of the first and last element to be used .

players = ['charles', 'martina', 'michael', 'florence', 'eli'] 
print(players[1:3])

If the first index is not specified ,Python Will automatically start at the beginning of the list .

To end the slice at the end of the list , A similar grammar can be used .

A negative index returns the element at the corresponding distance from the end of the list , For example, the last three players , Slicing can be used players[-3:] .

Be careful The third value can be specified in square brackets representing slices . This value tells Python Extract every number of elements within the specified range .

4.4.2 Traversing slices

If you want to traverse parts of the list , Can be found in for Use slices in the loop .

4.4.3 Copy list

To copy a list , You can create a slice that contains the entire list , The method is to omit both the starting index and the ending index ([:]).

my_foods = ['pizza', 'falafel', 'carrot cake'] 
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)

If you want to pass friend_foods = my_foods To copy the table , It doesn't work .

Because here will my_foods Assign to friend_foods, Rather than my_foods A copy of is assigned to friend_foods. This kind of grammar actually makes Python Put the new variable friend_foods Relating to already associated with my_foods Associated list , So these two variables point to the same list . 

Give it a try

practice 4-10: section

Choose a program you write in this chapter , Add a few lines of code at the end , To complete the following tasks .

▲ Print a message “The first three items in the list are:”, Then use slices to print the first three elements of the list .

▲ Print a message “Three items from the middle of the list are:”, Then use the slice to print the middle three elements of the list .

▲ Print a message “The last three items in the list are:”, Then use the slice to print the last three elements of the list .

practice 4-11: Your pizza , My pizza

Before you finish the exercise 4-1 And in the program , Create a copy of the pizza list , And assign it to a variable friend_pizzas, Then complete the following tasks .

▲ Add a pizza to the original pizza list .

▲ In the list friend_pizzas Add another pizza .

▲ Verify that there are two different lists . So , Print a message “My favorite pizzas are:”, Use one more for Loop to print the first list ; Print a message “My friend's favorite pizzas are:”, Use one more for Loop to print the second list . Verify that the new pizza is added to the correct list .

practice 4-12: Use multiple loops

In this section , To save space , Program foods.py Every version of is not used for Loop to print the list . Please select a version of foods.py, Write two for loop , Print out the list of foods .

4.5 Tuples

Python A value that cannot be modified is called immutable , And immutable lists are called tuples .

4.5.1 Define and access tuples

Tuples look like lists , But use parentheses instead of square brackets to identify . After defining tuples , You can use the index to access its elements , It's like accessing list elements .

dimensions = (200, 50)
print(dimensions[0])

If you modify tuples dimensions An element of , There will be mistakes :

Traceback (most recent call last):
  File "E:\...\dimensions.py", line 2, in <module>
    dimensions[0]=100
TypeError: 'tuple' object does not support item assignment

Be careful Strictly speaking , Tuples are identified by commas , Parentheses just make tuples look cleaner 、 Clearer . If you want to define a tuple that contains only one element , This element must be followed by a comma :dimensions = (200, ) 

4.5.2 Traverse all the values in the tuple

Like a list , You can also use for Loop through all the values in the tuple

4.5.3 Change tuple variable

Although the elements of tuples cannot be modified , But you can assign values to variables associated with tuples .

dimensions = (200, )
dimensions=(300,600)

Give it a try

practice 4-13: Buffet

There is a cafeteria , There are only five simple foods . Please think of five simple foods , And store it in a tuple .▲ Use one for Cycle to print out all five foods offered by the restaurant .

▲ Try to modify one of the elements , verify Python I'll really refuse you to do so .

▲ The restaurant adjusted the menu , Replaced two of the foods it provided . Please write such a code block : Assign values to tuple variables , And use a for Loop prints each element of the new element group .

4.6 Format the code

4.6.1 Formatting guide

Python Improvement proposal (Python Enhancement Proposal,PEP).

PEP 8 It's the oldest PEP One of , towards Python The programmer provides a code format guide .

4.6.2 Indent

PEP 8 Four spaces are recommended for each indentation level .

You should definitely use tab keys when writing code , But be sure to set up the editor , Make it insert spaces in the document instead of tabs .

If you mix tabs and spaces , All tabs in the file can be converted to spaces , Most editors provide this functionality .

4.6.3 governor

quite a lot Python Programmers suggest that each line should not exceed 80 character .

PEP 8 It is also suggested that the number of notes should not exceed 72 character .

In most editors , A visual sign can be set ( It's usually a vertical line ), Let you know where the line that can't be crossed is .

Be careful appendix B Describes how to configure the text editor , Make it insert four spaces when you press the tab key , And display a vertical reference line , Help you comply with the president's no more than 79 Character conventions .

4.6.4 Blank line

Separate the different parts of the program , You can use the blank line .

4.6.5 Other formatting guidelines

And so on Python When the structure , Let's share other related PEP 8 guide .

Give it a try

practice 4-14:PEP 8

Please visit Python Website and search “PEP 8 — Style Guide for PythonCode”, read PEP 8 Formatting guide . At present , These guidelines do not apply in many cases , But you can take a glance at .

practice 4-15: Code review

Choose three from the programs written in this chapter , according to PEP 8 The guide modifies them .

▲ Use four spaces for each level of indentation . Set the text editor you use , Make it when you press Tab Key to insert four spaces . If you haven't done that yet , Do it now ( About how to set up , Please refer to the appendix B).

▲ Each line should not exceed 80 character . Set the editor you use , Make it in the 80 A vertical reference line is displayed at characters .

▲ Do not use too many blank lines in program files .

4.7 Summary

In this chapter , You studied. : How to deal with the elements in the list efficiently ; How to use for Loop through the list ,Python How to determine the structure of a program according to indentation , And how to avoid some common indentation errors ; How to create a simple list of numbers , And some operations that can be performed on the number list ; How to use part of the list and copy the list through slicing . You also learned tuples ( It provides a degree of protection against values that should not change ), And how to format as the code becomes more and more complex , Make it easy to read .

原网站

版权声明
本文为[axinawang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/175/202206240409227540.html