Python 有特定的内置函数,因此它支持多个顺序容器中的许多循环技术。这些循环函数和方法对于竞争性编码非常有用。它可以在不同的项目中使用,在这些项目中,用户必须使用一些特定的循环技术来维护程序的整个结构。这些技术有助于节省时间和内存空间,因为用户不必为传统的循环方法声明额外的变量。
这些循环技术用在哪里?
不同类型的循环技术用于用户不必操作代码结构或整个容器顺序的地方。相反,用户必须打印单次使用实例的元素,并且容器中不会发生原地更改。这些也可以用来节省时间和内存。
使用 Python 数据结构的循环技术:
- enumerate():enumerate()函数用于循环遍历容器,并使用特定索引中的值打印索引号。
示例:
for key, value in enumerate(['Joe', 'waited', 'for', 'the', 'train', ',', 'but', 'the', 'train', 'was', 'late', '.']):
print(key, value)
输出:
0 Joe
1 waited
2 for
3 the
4 train
5 ,
6 but
7 the
8 train
9 was
10 late
11 .
- zip():zip()函数用于通过按顺序打印两个相似容器的值来组合这两个容器,如 dict 与 dict 或 list 与 list。该循环仅在较小容器结束后存在。
示例:
# first, we will initialize the list
question = ['animal', 'shape', 'time']
answer = ['tiger', 'square', '11 o clock']
# the zip() function will be used for combining these two containers
for question, answer in zip(question, answer):
print('What is this {0}? this is {1}.'.format(question, answer))
输出:
What is this animal? this is tiger.
What is this shape? this is square.
What is this time? this is 11 o clock.
- items():items()函数用于循环遍历字典,并按顺序打印关键字及其值。
示例:
dict = { "Joe" : "waited", "for" : "the", "train" : "but", "the" : "train", "was" : "late" }
# the use items for print the dictionary key-value pair
print ("The key value pair by using items is : ")
for a, b in dict.items():
print(a, b)
输出:
The key value pair by using items is :
Joe waited
for the
train but
the train
was late
- sorted():sorted()函数用于按排序顺序打印容器。这个函数不排序容器,但是它用于按照排序的顺序打印容器。用户可以使用 set()函数和 sorted()函数来删除输出中的重复值。
例 1:
# first, initialize the list
list = [ 1 , 4, 6, 7, 1, 2, 4 ]
# using sorted() to print the list in sorted order
print ("The list in sorted order is : ")
for a in sorted(list) :
print (a, end = " ")
print ("\r")
# now use the sorted() function and set() function for printing the list in sorted order
# use of set() to removes duplicates in output value.
print ("The list in sorted order (without duplicates) is : ")
for a in sorted(set(list)) :
print (a, end = " ")
输出:
The list in sorted order is :
1 1 2 4 4 6 7
The list in sorted order (without duplicates) is :
1 2 4 6 7
例 2:
# initializing list
list2 = ['Joe', 'waited', 'for', 'the', 'train', 'but', 'the', 'train', 'was', 'late']
# now use the sorted() function and set() function for printing the list in sorted order
for sentence in sorted(set(list2)):
print(sentence)
输出:
Joe
but
for
late
the
train
waited
was
- reversed():reserved()函数用于以相反的顺序打印容器的值。
例 1:
# initializing list
list = [ 1 , 3, 5, 7, 9, 11, 13, 15, 17, 19, 21 ]
# by using the revered() function for printing the list in reversed order
print ("The list in reversed order is : ")
for a in reversed(list) :
print (a, end = " ")
输出:
The list in reversed order is :
21 19 17 15 13 11 9 7 5 3 1
例 2:
for b in reversed(range(1, 20, 2)):
print (b)
输出:
19
17
15
13
11
9
7
5
3
1
结论
在本教程中,我们讨论了有助于节省内存和时间的不同类型的裁剪技术。