在本教程中,您将学习Python循环技术。在上一个教程中,我们讨论了Python pass语句。如果您感兴趣,可以单击此链接去读那个教程。
Python循环
我们了解到Python循环以前。但是Python的循环比其他语言更灵活。我们可以在这里做更多有趣的事情。Python&&8217;s for loop是多功能的。我们将看到一些关于这个的例子。
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()
function. reversed()
function reverse the order of a sequence. Have a look over the following code.
#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 order。为此,您必须使用sorted()
function. sorted()
function sort the order of a sequence. Have a look over the following code.
#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()
function. The following code will help understand the thing.
#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 loop可以同时遍历两个或多个序列。例如,在一个序列中,你有一个名字列表,在另一个序列中,你有对应的人的爱好列表。所以你必须打印出个人的名字和他们的爱好。所以下面的例子将指导您这样做。
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
>>>
如果你多练习,一天一天你会学到很多关于python的有趣的东西。这就是Python循环示例的全部内容。希望你能理解。如有任何疑问,请在下面发表意见。 #快乐编码