Python循环示例

时间:2020-02-23 14:42:58  来源:igfitidea点击:

在本教程中,您将学习Python循环技术。

Python循环

我们之前学习过Python循环。
但是Python的循环比其他语言更灵活。
我们可以在这里做更多有趣的事情。
Python的for循环功能多样。
我们将看到一些有关此的示例。

Python遍历序列

这是Python for loop的一个非常常见的例子。
假设我们有一个项目序列,我们需要一个遍历该序列。
我们可以像这样使用for循环:

#initialize a list
items = ["apple", 1, 4, "exit", "321"]

#for each item in the list traverse the list
for item in items:
      # print the item
      print (item),

以下代码的输出将是

================== RESTART: /home/imtiaz/Desktop/ltech1.py ==================
apple 1 4 exit 321
>>>

Python以相反顺序循环显示序列

您也可以按相反的顺序打印前面的示例。
为此,您必须使用reversed()函数。
reversed()函数反转序列的顺序。
看一下下面的代码。

#initialize a list
items = ["apple", 1, 4, "exit", "321"]

#for each item in the list traverse the list
#before that reverse the order of the list
for item in reversed(items):
      # print the item
      print (item),

输出将是

================== RESTART: /home/imtiaz/Desktop/ltech2.py ==================
321 exit 4 1 apple
>>>

Python按排序顺序遍历序列

您还可以打印前面的示例int排序顺序。
为此,您必须使用sorted()函数。
sorted()函数对序列的顺序进行排序。
看一下下面的代码。

#initialize a list
items = [7, 1, 4, 9, 3]

#for each item in the sorted list, traverse the list
for item in sorted(items):
      # print the item
      print (item),

输出将是

================== RESTART: /home/imtiaz/Desktop/ltech4.py ==================
1 3 4 7 9
>>>

枚举值和对应的索引

您还可以枚举序列值及其索引。
为此,您必须使用enumerate()函数。
以下代码将有助于您理解。

#initialize a list
items = [7, 1, 4, 9, 3]

#for each item in the list traverse the list
for index,value in enumerate(items):
      # print the index along with their value
      print ("value of "+str(index)+" is = "+str(value))

遍历两个或者多个序列

使用python for循环,您可以同时遍历两个或者多个序列。
例如,在一个序列中,您有一个姓名列表,在另一个序列中,您有相应人员的爱好列表。
因此,您必须打印人的名字以及他们的爱好。
因此,以下示例将指导您执行此操作。

names = [ 'Alice', 'Bob', 'Trudy' ]
hobbies = [ 'painting', 'singing', 'hacking']
ages = [ 21, 17, 22 ]

#combine those list using zip() function
for person,age, hobby in zip(names,ages,hobbies):
      print (person+" is "+str(age)+"  years old and his/her hobby is "+hobby)

输出将是

Alice is 21  years old and his/her hobby is painting
Bob is 17  years old and his/her hobby is singing
Trudy is 22  years old and his/her hobby is hacking
>>>