Python learning from the introductory operation list
4.1 Traverse the entire list
We often need to traverse all elements in the list and perform the same operation on each list. This is useful when doing repetitive work, repetitive work. For example, in a game, you may need to translate each interface element the same distance; for a list containing numbers, you may need to perform the same statistical operation on each element; in a website, you may need to display each title in 3 articles . When you need to perform the same operation on each element in the list, you can use the for loop in Python.
If we have a list of magicians, we need to print out the name of each magician. To do this, we could get each name in the list individually, but this would cause a lot of problems. For example, if the list is too long, it will contain a lot of duplicate code. Additionally, the code must be modified every time the length of the list changes. By using a for loop, you can let Python handle these problems.
The following uses a for loop to print all the names in the magician's list:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
1 2 3 4 5 6 7 8 9 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
1 2 3 4 5 6 7 8 9 |
|
1 2 3 4 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
1 2 3 4 5 6 7 8 9 10 |
|
1 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
1 2 3 4 5 6 7 8 9 10 11 |
|
1 2 3 4 5 |
|
1 2 3 4 5 6 |
|
1 2 3 4 5 6 7 8 9 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
1 2 3 |
|
1 |
|
1 2 3 4 5 6 7 8 |
|
1 2 3 |
|
1 2 3 4 5 6 7 8 |
|
When using assignment to generate friend_foods, my_foods and friend_food s shares a memory, and no new memory is opened in Python. The memory, as shown in the picture above, is just related together, so when we assign a value, it becomes like this:
When we add a new element to the my_foods list when we add elements to friend_foods, the new elements are also added to the original memory list, so when assignment is used, Python will not open up new memory, but will just merge the two The two variables are related together, as shown in the figure above, so the final results of the two are still the same.
Let’s look at the situation when using slices:
Since slicing is used, slicing opens up a new memory list for storing friend_foods , when we add a new element, as shown below:
Since it is a list of two different memory allocations, when adding a new element to my_foods, only add it to in the memory list of my_foods; when adding new elements to friend_foods, new elements are only added to the memory list to which friend_foods belongs, so the output results are different.
Therefore, the operating mechanisms of assignment and slicing in Python are different. When we assign values, we must pay attention to this. We did not pay much attention to it before, but we will pay attention to it in the future. Especially when copying operations.
Summary: When we make one parameter equal to another parameter, directly a = b, this is an assignment. When an assignment is made between two parameters, it is a shared memory, Python
There is no new space inside.
Give it a try
4-10 Slicing: Choose a program you wrote in this chapter and add a few lines of code at the end to complete the following tasks.
1. Print the message "The first three items in the list are:", use slicing to print the first three elements of the list;
2. Print the message "Three items from the middle of list are: ", use slicing to print the three elements in the middle of the list;
3. Print the message "The last three items in the list are: ", use slicing to print the last three elements of the list .
4-11 Your Pizza and My Pizza: In the program you wrote to complete Exercise 4-1, create a copy of the pizza list and store it in the variable friend_pizzas. Complete the following tasks .
1. Add a pizza to the original pizza list;
2. Add another pizza to the friend_pizzas list;
3. Verify that you have two Different lists. To do this, print the message "My favorite pizzas are:", and then use a for loop to print the second list. Verify that added pizzas are added to the correct list.
4-10: This question mainly examines the representation method of list slices. How to represent list slices, especially L.[-1] represents the last element. The use of this method is very critical. Examine the last few elements. It will be used every time. The representation of list slicing is from the number of elements to the number of elements, separated by colons in the middle.
digits = [2,3,8,9,0,3,5,7]
print("The first three items in the list are: ")
print(digits[: 3])
print("\nThree items from the middle of the list are: ")
print(digits[2:5])
print("\nThe last three items in the list are: ")
print(digits[-3:])
The running result is as follows:
The first three items in the list are:
[2, 3, 8]
Three items from the middle of the list are:
[8, 9, 0]
The last three items in the list are:
[3, 5, 7]
4-11 This question mainly examines the use of slicing and the method of copying lists. List copying must be completed through slicing, which is determined by the working principle of Python.
pizzas = ["New York Style","Chicago Style","California Style"]
friend_pizzas = pizzas[:]
pizzas.append("noodle" )
friend_pizzas.append("rice")
print("My favorite pizzas are: ")
for pizza in pizzas:
print(pizza)
print(pizzas)
print("\nMy friend's favorite pizzas are: ")
for friend_pizza in friend_pizzas:
print(friend_pizza)
print(friend_pizzas)
Run result:
My favorite pizzas are:
New York Style
Chicago Style
California Style
noodle
['New York Style', 'Chicago Style', 'California Style', 'noodle' ]
My friend's favorite pizzas are:
New York Style
Chicago Style
California Style
rice
['New York Style', 'Chicago Style', 'California Style', 'rice']
4.5 Yuanzu
Lists are ideal for storing data sets that may change while the program is running. Lists are modifiable, which is crucial when working with a list of users for a website or a list of characters in a game. However, sometimes we need to create a series of immutable elements, and Yuanzu can meet this need. Python calls values that cannot be modified immutable, and immutable lists are called primitives.
4.5.1 Definition of Yuanzu
Yuanzu looks like a list, but is marked with parentheses instead of square brackets. Once a tuple is defined, its elements can be accessed using indexes, just like list elements.
For example, if you have a rectangle whose size should not change, you can store its length and width in a tuple, ensuring that they cannot be modified:
dimensions.py
dimensions = (200,50)
print(dimensions[0])
print(dimensions[1])
We first define the original dimensions, for which we use parentheses instead of square brackets. Next, we print each element of the tuple separately, using the same syntax we use when accessing list elements:
200
50
We know that the tuple is by definition The elements cannot be modified. Let's try to modify an element in the element dimensions and see what the result is:
dimensions = (200,50)
dimensions[0] = 250
print(dimensions) The code attempts to modify the value of the first element, causing Python to return a type error message. Since attempts to modify the ancestor are prohibited, Python points out that values cannot be assigned to elements of the ancestor:
Traceback (most recent call last):
File "/home/zhuzhu/title4/dimensions.py ", line 2, in module>
dimensions[0] = 250
TypeError: 'tuple' object does not support item assignment
Python reports an error when the code tries to modify the dimensions of the rectangle, which is good because that’s what we want.
4.5.2 Traverse all values in the ancestor
像列表一样,也可以使用for循环来遍历元组中的所有值:
dimensions = (200,50)
for dimension in dimensions:
print(dimension)
就像遍历列表时一样,Python返回元组中所有的元素:
200
50
4.5.3 修改元组变量
虽然不能修改元组的元素,但可以给存储元组的变量赋值。因此,如果要修改前述矩形的尺寸,可重新定义整个元组:
dimensions = (200,50)
print("Original dimensions: ")
for dimension in dimensions:
print(dimension)
dimensions = (400,100)
print("\nModified dimensions: ")
for dimension in dimensions:
print(dimension)
我们首先定义了一个元组,并将其存储的尺寸打印了出来;接下来,将一个新元组存储到变量dimensions中;然后,打印新的尺寸。这次,Python不会报告任何错误,因为给元组变量赋值是合法的:
Original dimensions:
200
50
Modified dimensions:
400
100
相比于列表,元组是更简单的数据结构.如果需要存储的一组值在程序的整个生命周期内都不变,可使用元组。
动手试一试
4-13 自助餐: 有一家自助式餐厅,只提供五种简单的食品。请想出五种简单的食品,并将其存储在一个元祖中。
1、使用一个for循环将该餐馆提供的五种食品都打印出来;
2、尝试修改其中的一个元素,核实Python确实会拒绝我们这样做;
3、餐馆调整了菜单,替换了它提供的某中两种实物。请编写一个这样的代码块;给元组变量赋值,并使用一个for循环将新元组中的每个元素都打印出来。
分析:本题主要考察元组的性质及用法,我们知道,元组中的元素是不可以修改的,但是元组是可以重新赋值的,我们虽然不能修改元组中的元素,但是我们可以整体修改元组,元组其他的性质跟列表的性质都是一样的,就是不能对元组本身就行修改,比如添加,删除,赋值等。
cafeterias = ("rice","noodle","porridge","hamburger","pizza")
for cafeteria in cafeterias:
print(cafeteria)
cafeterias[-1] = "dami"
运行结果如下:
rice
noodle
porridge
hamburger
pizza
Traceback (most recent call last):
File "/home/zhuzhu/title4/Cafeterias.py", line 5, in
cafeterias[-1] = "dami"
TypeError: 'tuple' object does not support item assignment
从运行结果可以看出,当我们试图修改元组的元素是,发生了错误,提示我们不能修改元组的元组值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
|
Original menu:
rice
noodle
porridge
hamburger
pizza
Modified menu:
pizza
hamburger
rice
milk
Drumsticks
The above is the detailed content of Python learning from the introductory operation list. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The speed of mobile XML to PDF depends on the following factors: the complexity of XML structure. Mobile hardware configuration conversion method (library, algorithm) code quality optimization methods (select efficient libraries, optimize algorithms, cache data, and utilize multi-threading). Overall, there is no absolute answer and it needs to be optimized according to the specific situation.

It is impossible to complete XML to PDF conversion directly on your phone with a single application. It is necessary to use cloud services, which can be achieved through two steps: 1. Convert XML to PDF in the cloud, 2. Access or download the converted PDF file on the mobile phone.

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

It is not easy to convert XML to PDF directly on your phone, but it can be achieved with the help of cloud services. It is recommended to use a lightweight mobile app to upload XML files and receive generated PDFs, and convert them with cloud APIs. Cloud APIs use serverless computing services, and choosing the right platform is crucial. Complexity, error handling, security, and optimization strategies need to be considered when handling XML parsing and PDF generation. The entire process requires the front-end app and the back-end API to work together, and it requires some understanding of a variety of technologies.

XML can be converted to images by using an XSLT converter or image library. XSLT Converter: Use an XSLT processor and stylesheet to convert XML to images. Image Library: Use libraries such as PIL or ImageMagick to create images from XML data, such as drawing shapes and text.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

The steps to convert XML to MP3 include: Extract audio data from XML: parse the XML file, find the base64 encoding string containing the audio data, and decode it into binary format. Encode the audio data to MP3: Install the MP3 encoder and set the encoding parameters, encode the binary audio data to MP3 format, and save it to a file.

There are several ways to modify XML formats: manually editing with a text editor such as Notepad; automatically formatting with online or desktop XML formatting tools such as XMLbeautifier; define conversion rules using XML conversion tools such as XSLT; or parse and operate using programming languages such as Python. Be careful when modifying and back up the original files.
