While creating applications with python we generally need to use list like or array data structures. If we will iterate over list like data we generally use for
loop. But some times the data may have multiple dimensions. In order to cope with multiple dimensions we have to define nested for
loops.
在使用python创建应用程序时,我们通常需要使用类似列表或数组的数据结构。 如果我们要遍历像数据这样的列表,通常会使用for
循环。 但是有时数据可能具有多个维度。 为了应付多个维度,我们必须定义嵌套的for
循环。
嵌套循环 (Nested For Loop)
for
loops can be nested inside each other. There is no restriction about the count of inner for
loop. But using unnecessary nested loops will create performance bottlenecks. We can use following syntax for nested loops.
for
循环可以相互嵌套。 对于内部for
循环的数量没有限制。 但是,使用不必要的嵌套循环将创建性能瓶颈。 我们可以对嵌套循环使用以下语法。
for A in LIST1:
for B in LIST2:
for C in LIST3:
print(A,B,C)
具有多个列表的嵌套循环 (Nested Loop With Multiple Lists)
There are different use cases for nested for loops in Python. In this part we will examine nested for loops with multiple lists. In this example we have lists named name
, car
, number
. We will nest all lists with 3 for
and then print them to the console.
Python中嵌套的for循环有不同的用例。 在这一部分中,我们将检查嵌套的具有多个列表的循环。 在此示例中,我们列出了名为name
, car
, number
列表。 我们将巢3的所有列表for
,然后将它们打印到控制台。
names=['ismail','ali','elif']
cars=['mercedes','porshe','hyundai']
numbers=[1,2,3]
for name in names:
for car in cars:
for number in numbers:
print(name+" has "+str(number)+" "+car)
![Nested Loop With Multiple Lists](https://i-blog.csdnimg.cn/blog_migrate/19361ac5a4eda0a90a6d2850527284bc.png)
具有单个多维列表的嵌套循环(Nested Loop With Single Multi Dimension List)
Another popular use case for nested is is iterating over multi dimension lists. Multi dimension list have a list where its elements are list too. Here we will use list named persons where each element is a list which contains personal information.
嵌套的另一个流行用例是遍历多维列表。 多维列表也有一个列表,其元素也在列表中。 在这里,我们将使用名为人员的列表,其中每个元素都是包含个人信息的列表。
persons=[['ismail', 30], ['ali', 5], ['elif', 10]]
for person in persons:
for value in person:
print(value)
![Nested Loop With Single Multi Dimension List](https://i-blog.csdnimg.cn/blog_migrate/1b733138eee4494722803185f8be97b3.png)
具有多范围功能的嵌套循环(Nested Loop with Multiple Range Function)
range()
function is used to create number lists in a very efficient and easy way. We have all ready examined the range()
function and relate topic in the following tutorial.
range()
函数用于以非常有效和简便的方式创建数字列表。 我们都准备好检查range()
函数并在以下教程中涉及主题。
Python For Loop Tutorial With Examples and Range/Xrange Functions
带有示例和Range / Xrange函数的Python For循环教程
We will create nested loop with two range()
function where each of them starts from 1 and ends at 5. We will multiple each of them
我们将创建带有两个range()
函数的嵌套循环,其中每个函数都从1开始,以5结尾。
for x in range(1,5):
for y in range(1,5):
print(x*y)
![Nested Loop with Multiple Range Function](https://i-blog.csdnimg.cn/blog_migrate/e438155606e8618ee01e221817a601b7.png)
翻译自: https://www.poftut.com/how-to-create-nested-for-loops-in-python/