Python 通过某些内置函数在各种顺序容器中支持各种循环技术。这些方法主要在竞争性编程中非常有用,并且在需要使用循环来维护代码整体结构的特定技术的各种项目中也非常有用。节省了大量的时间和内存空间,因为不需要声明我们在传统循环方法中声明的额外变量。
不同的循环技术主要适用于我们不需要实际操作整个容器的结构和顺序的地方,而只打印一次性实例的元素,容器中不会发生就地更改。这也可以在实例中使用以节省时间。
方式 1:使用 enumerate(): enumerate() 用于循环遍历容器,打印索引号以及该特定索引中存在的值。
0 The 1 Big 2 Bang 3 Theory
输出:
# python code to demonstrate working of enumerate() for key, value in enumerate(['Geeks', 'for', 'Geeks', 'is', 'the', 'Best', 'Coding', 'Platform']): print(value, end=' ')
Geeks for Geeks is the Best Coding Platform
方式2:使用zip(): zip()用于组合2个相似的容器(list-list或dict-dict)顺序打印值。循环仅存在到较小容器结束为止。
例子
# python code to demonstrate working of zip() # initializing list questions = ['name', 'colour', 'shape'] answers = ['apple', 'red', 'a circle'] # using zip() to combine two containers # and print values for question, answer in zip(questions, answers): print('What is your {0}? I am {1}.'.format(question, answer))
What is your name? I am apple. What is your color? I am red. What is your shape? I am a circle.
方式三:使用iteritems(): iteritems()用于循环遍历字典,按顺序打印字典键值对,Python 3版本之前使用。
方式 4:使用 items(): items() 在字典上执行与 iteritems() 类似的任务,但与 iteritems() 相比有一定的缺点。
示例1:
# python code to demonstrate working of items() d = {"geeks": "for", "only": "geeks"} # iteritems() is renamed to items() in python3 # using items to print the dictionary key-value pair print("The key value pair using items is : ") for i, j in d.items(): print(i, j) # python code to demonstrate working of items()` `d ``=` `{``"geeks"``: ``"for"``, ``"only"``: ``"geeks"``}` `# iteritems() is renamed to items() in python3``# using items to print the dictionary key-value pair``print``(``"The key value pair using items is : "``)``for` `i, j ``in` `d.items():`` ``print``(i, j)
The key value pair using iteritems is : geeks for only geeks 只有极客
示例2:
# python code to demonstrate working of items() king = {'Akbar': 'The Great', 'Chandragupta': 'The Maurya', 'Modi': 'The Changer'} # using items to print the dictionary key-value pair for key, value in king.items(): print(key, value)
Akbar The Great Chandragupta The Maurya Modi The Changer
方式5:使用sorted(): sorted()用于打印容器的排序顺序。它不会对容器进行排序,而只是按排序顺序打印 1 个实例的容器。可以组合使用set() 来删除重复出现的情况。
# python code to demonstrate working of sorted() # initializing list lis = [1, 3, 5, 6, 2, 1, 3] # using sorted() to print the list in sorted order print("The list in sorted order is : ") for i in sorted(lis): print(i, end=" ") print("\r") # using sorted() and set() to print the list in sorted order # use of set() removes duplicates. print("The list in sorted order (without duplicates) is : ") for i in sorted(set(lis)): print(i, end=" ")
The list in sorted order is : 1 1 2 3 3 5 6 The list in sorted order (without duplicates) is : 1 2 3 5 6
# python code to demonstrate working of sorted() # initializing list basket = ['guave', 'orange', 'apple', 'pear', 'guava', 'banana', 'grape'] # using sorted() and set() to print the list # in sorted order for fruit in sorted(set(basket)): print(fruit)
apple banana grape guava guave orange pear
方式6:使用reverse(): reverse()用于以相反的顺序打印容器 的值。它并不反映对原始列表的任何更改
# python code to demonstrate working of reversed() # initializing list lis = [1, 3, 5, 6, 2, 1, 3] # using reversed() to print the list in reversed order print("The list in reversed order is : ") for i in reversed(lis): print(i, end=" ")
The list in reversed order is : 3 1 2 6 5 3 1
# python code to demonstrate working of reversed() # using reversed() to print in reverse order for i in reversed(range(1, 10, 3)): print(i)
7 4 1
在此示例中,我们使用 while 循环来递增名为 count 的变量。在循环内部,我们使用 if 语句来检查 count 是否等于 3。如果是,我们打印一条消息。
方法:
将 count 变量初始化为 0 使用 while 循环重复执行一段代码,只要 count 小于 5 在循环内,使用 if 语句检查 count 是否等于 3 如果 count 为 3,则打印一条消息 Increment每次迭代结束时计数加 1
# Example variable count = 0 # Loop while count is less than 5 while count < 5: if count == 3: print("Count is 3") count += 1
输出
Count is 3
时间复杂度:O(n),其中n是count达到5所需的迭代次数。
辅助空间:O(1),因为整个代码中仅使用一个变量(计数)。
原文链接:codingdict.net