Python 中的循环技术

2024 年 8 月 29 日 | 4 分钟阅读

Python 提供了特定的内置函数,因此它支持多种序列容器的循环技术。这些循环函数和方法对于竞争性编程非常有用。它们可以用于用户需要使用一些特定的循环技术来维护程序整体结构的各种项目中。这些技术有助于节省时间和内存空间,因为用户无需为传统的循环方法声明额外的变量。

这些循环技术用在哪里?

不同类型的循环技术用于用户无需操作代码结构或整个容器顺序的地方。相反,用户需要为单次使用实例打印元素,并且容器不会发生原地更改。这些也可以用于节省时间和内存。

使用 Python 数据结构进行循环的技术

  • enumerate(): enumerate() 函数用于循环遍历容器,并打印索引号以及该特定索引中的值。

示例

输出

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,通过按顺序打印它们的值。循环将在较小容器结束时结束。

示例

输出

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() 函数用于循环遍历字典,并按顺序打印键及其值。

示例

输出

The key value pair by using items is : 
Joe waited
for the
train but
the train
was late
  • sorted(): sorted() 函数用于按排序顺序打印容器。此函数不会对容器进行排序,而是用于按排序顺序打印容器,例如。用户可以使用 set() 函数与 sorted() 函数结合使用以消除输出中的重复值。

示例 1

输出

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

输出

Joe
but
for
late
the
train
waited
was
  • reversed(): reversed() 函数用于按相反顺序打印容器的值。

示例 1

输出

The list in reversed order is : 
21 19 17 15 13 11 9 7 5 3 1

示例 2

输出

19
17
15
13
11
9
7
5
3
1

结论

在本教程中,我们讨论了有助于节省内存和时间的各种循环技术。