Python 简明教程

Python - Loop Arrays

循环用于反复执行一段代码块。在 Python 中,有两种类型的循环,命名为 for loopwhile loop 。由于数组对象就像一个序列,因此您可以借助循环来迭代其元素。

Loops are used to repeatedly execute a block of code. In Python, there are two types of loops named for loop and while loop. Since the array object behaves like a sequence, you can iterate through its elements with the help of loops.

遍历 arrays 的原因是为了执行诸如访问、修改、搜索或聚合数组元素之类的操作。

The reason for looping through arrays is to perform operations such as accessing, modifying, searching, or aggregating elements of the array.

Python for Loop with Array

当迭代次数已知时,使用 for 循环。如果我们将其与诸如数组之类的可迭代对象结合使用,那么该迭代将在遍历数组中每个元素后继续进行。

The for loop is used when the number of iterations is known. If we use it with an iterable like array, the iteration continues until it has iterated over every element in the array.

Example

以下示例演示了如何使用“for”循环遍历数组:

The below example demonstrates how to iterate over an array using the "for" loop −

import array as arr
newArray = arr.array('i', [56, 42, 23, 85, 45])
for iterate in newArray:
   print (iterate)

以上代码将产生以下结果:

The above code will produce the following result −

56
42
23
85
45

Python while Loop with Array

在 while 循环中,迭代将继续进行,只要指定的条件为真。当您将此循环与数组结合使用时,在进入循环之前初始化一个循环变量。此变量通常表示用于访问数组中元素的索引。在 while 循环内部,遍历数组元素并手动更新循环变量。

In while loop, the iteration continues as long as the specified condition is true. When you are using this loop with arrays, initialize a loop variable before entering the loop. This variable often represents an index for accessing elements in the array. Inside the while loop, iterate over the array elements and manually update the loop variable.

Example

以下示例显示了如何使用 while 循环遍历数组:

The following example shows how you can loop through an array using a while loop −

import array as arr

# creating array
a = arr.array('i', [96, 26, 56, 76, 46])

# checking the length
l = len(a)

# loop variable
idx = 0

# while loop
while idx < l:
   print (a[idx])
   # incrementing the while loop
   idx+=1

执行以上代码,将显示以下输出:

On executing the above code, it will display the following output −

96
26
56
76
46

Python for Loop with Array Index

我们可以使用内置的 len() 函数查找数组长度。使用它创建范围对象以获取索引序列,然后在 for 循环中访问数组元素。

We can find the length of array with built-in len() function. Use it to create a range object to get the series of indices and then access the array elements in a for loop.

Example

下面的代码说明如何使用 for 循环和数组索引。

The code below illustrates how to use for loop with array index.

import array as arr
a = arr.array('d', [56, 42, 23, 85, 45])
l = len(a)
for x in range(l):
   print (a[x])

运行上述代码后,将显示以下输出:

On running the above code, it will show the below output −

56.0
42.0
23.0
85.0
45.0