Python 简明教程

Python - Loop Lists

Loop Through List Items

在 Python 中循环浏览列表项目是指遍历列表中的每个元素。我们这样做是为了对每个项目执行所需的操作。这些操作包括列表修改、条件操作、字符串操作、数据分析等。

Looping through list items in Python refers to iterating over each element within a list. We do so to perform the desired operations on each item. These operations include list modification, conditional operations, string manipulation, data analysis, etc.

Python 提供了各种用于循环浏览 list 项目的方法,最常见的是 for loop 。我们还可以使用 while loop 遍历列表项目,尽管它需要显式处理循环控制变量,即索引。

Python provides various methods for looping through list items, with the most common being the for loop. We can also use the while loop to iterate through list items, although it requires additional handling of the loop control variable explicitly i.e. an index.

Loop Through List Items with For Loop

Python 中的 for 循环用于遍历序列(如列表、元组、字典、字符串或范围)或任何其他可迭代对象。它允许您为序列中的每个项目重复执行一个代码块。

A for loop in Python is used to iterate over a sequence (like a list, tuple, dictionary, string, or range) or any other iterable object. It allows you to execute a block of code repeatedly for each item in the sequence.

在 for 循环中,您可以使用变量访问序列中的每个项目,从而允许您基于该项目的价值执行操作或逻辑。我们可以遍历列表项目通过 for 循环遍历列表中的每个项目。

In a for loop, you can access each item in a sequence using a variable, allowing you to perform operations or logic based on that item’s value. We can loop through list items using for loop by iterating over each item in the list.

Syntax

以下是在 Python 中使用 for 循环遍历列表中的项目的语法:

Following is the basic syntax to loop through items in a list using a for loop in Python −

for item in list:
   # Code block to execute

Example

在下面的例子中,我们使用一个 for 循环遍历列表“lst”中的每个元素,并在同一行用一个空格检索每个元素:

In the following example, we are using a for loop to iterate through each element in the list "lst" and retrieving each element followed by a space on the same line −

lst = [25, 12, 10, -21, 10, 100]
for num in lst:
   print (num, end = ' ')

Output

以下是上面代码的输出: -

Following is the output of the above code −

25 12 10 -21 10 100

Loop Through List Items with While Loop

Python 中的 while 循环用于重复执行一段代码块,只要一个指定的条件计算为“True”。

A while loop in Python is used to repeatedly execute a block of code as long as a specified condition evaluates to "True".

我们可以通过 while 循环遍历列表项目,方法是初始化一个索引变量,然后使用索引变量遍历列表,并递增它,直至到达列表末尾。

We can loop through list items using while loop by initializing an index variable, then iterating through the list using the index variable and incrementing it until reaching the end of the list.

Syntax

以下是在 Python 中使用 while 循环遍历列表中的项目的基本语法:

Following is the basic syntax for looping through items in a list using a while loop in Python −

while condition:
   # Code block to execute

Example

在下面的示例中,我们使用 while 循环遍历列表“my_list”中的每个项目。我们使用一个索引变量“index”顺序访问每个项目,在每次迭代后递增它以移动到下一个项目:

In the below example, we iterate through each item in the list "my_list" using a while loop. We use an index variable "index" to access each item sequentially, incrementing it after each iteration to move to the next item −

my_list = [1, 2, 3, 4, 5]
index = 0

while index < len(my_list):
   print(my_list[index])
   index += 1

Output

上述代码的输出如下:

Output of the above code is as follows −

1
2
3
4
5

Loop Through List Items with Index

索引是一个表示序列中元素位置的数字,从第一个元素的 0 开始,例如列表。

An index is a numeric value representing the position of an element within a sequence, such as a list, starting from 0 for the first element.

我们可以使用索引通过遍历对应于列表长度的索引范围并使用循环中的该索引来访问每个元素。

We can loop through list items using index by iterating over a range of indices corresponding to the length of the list and accessing each element using the index within the loop.

Example

本示例使用整数初始化列表“lst”,并创建一个对应于列表长度的索引范围。然后,它遍历该范围中的每个索引并打印列表“lst”中该索引处的值-

This example initializes a list "lst" with integers and creates a range of indices corresponding to the length of the list. Then, it iterates over each index in the range and prints the value at that index in the list "lst" −

lst = [25, 12, 10, -21, 10, 100]
indices = range(len(lst))
for i in indices:
   print ("lst[{}]: ".format(i), lst[i])

Output

我们得到了如下输出 −

We get the output as shown below −

lst[0]: 25
lst[1]: 12
lst[2]: 10
lst[3]: -21
lst[4]: 10
lst[5]: 100

Iterate using List Comprehension

Python中的列表推导是通过对可迭代对象的每个元素应用表达式来创建列表的简捷方式。这些表达式可以是算术运算、函数调用、条件表达式等。

A list comprehension in Python is a concise way to create lists by applying an expression to each element of an iterable. These expressions can be arithmetic operations, function calls, conditional expressions etc.

我们可以使用列表推导通过指定表达式和可迭代对象(如列表、元组、字典、字符串或范围)进行迭代。以下是语法-

We can iterate using list comprehension by specifying the expression and the iterable (like a list, tuple, dictionary, string, or range). Following is the syntax −

[expression for item in iterable]

这会将表达式应用于可迭代对象中的每个项并创建一个结果列表。

This applies the expression to each item in the iterable and creates a list of results.

Example

在这个示例中,我们使用列表推导来遍历数字列表中的每个数字、对每个数字求平方,并将平方的结果存储到新列表“squared_numbers”中 -

In this example, we use list comprehension to iterate through each number in a list of numbers, square each one, and store the squared result in the new list "squared_numbers" −

numbers = [1, 2, 3, 4, 5]
squared_numbers = [num ** 2 for num in numbers]
print (squared_numbers)

Output

我们得到了如下输出 −

We get the output as shown below −

[1, 4, 9, 16, 25]

Iterate using the enumerate() Function

Python中的enumerate()函数用于遍历可迭代对象,同时还提供每个元素的索引。

The enumerate() function in Python is used to iterate over an iterable object while also providing the index of each element.

我们可以通过将enumerate()函数应用于可迭代对象来进行遍历。以下是语法-

We can iterate using the enumerate() function by applying it to the iterable. Following is the syntax −

for index, item in enumerate(iterable):

这在迭代时提供可迭代对象每个元素的索引和项

This provides both the index and item of each element in the iterable during iteration

Example

在以下示例中,我们使用enumerate()函数遍历列表“fruits”并检索每个水果及其对应的索引-

In the following example, we are using the enumerate() function to iterate through a list "fruits" and retrieve each fruit along with its corresponding index −

fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
   print(index, fruit)

Output

我们得到了如下输出 −

We get the output as shown below −

0 apple
1 banana
2 cherry