我是靠谱客的博主 明亮机器猫,这篇文章主要介绍Python入门-循环技巧介绍,现在分享给大家,希望可以做个参考。

本篇文章给大家带来的内容是关于Python循环的技巧介绍,有一定的参考价值.
本文摘自千锋教育《Python快乐编程》

当在字典中循环时,用 items() 方法可将关键字和对应的值同时取出

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} >>> for k, v in knights.items(): ... print(k, v) ... gallahad the pure robin the brave

当在序列中循环时,用 enumerate() 函数可以将索引位置和其对应的值同时取出

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
>>> for i, v in enumerate(['tic', 'tac', 'toe']): ... print(i, v) ... 0 tic 1 tac 2 toe

当同时在两个或更多序列中循环时,可以用 zip() 函数将其内元素一一匹配。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> questions = ['name', 'quest', 'favorite color'] >>> answers = ['lancelot', 'the holy grail', 'blue'] >>> for q, a in zip(questions, answers): ... print('What is your {0}? It is {1}.'.format(q, a)) ... What is your name? It is lancelot. What is your quest? It is the holy grail. What is your favorite color? It is blue.

当逆向循环一个序列时,先正向定位序列,然后调用 reversed() 函数

复制代码
1
2
3
4
5
6
7
8
9
10
>>> for i in reversed(range(1, 10, 2)): ... print(i) ... 7 3

如果要按某个指定顺序循环一个序列,可以用 sorted() 函数,它可以在不改动原序列的基础上返回一个新的排好序的序列

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> for f in sorted(set(basket)): ... print(f) ... apple banana orange pear

有时可能会想在python循环时修改列表内容,一般来说改为创建一个新列表是比较简单且安全的

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
>>> import math >>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8] >>> filtered_data = [] >>> for value in raw_data: ... if not math.isnan(value): ... filtered_data.append(value) ... >>> filtered_data [56.2, 51.7, 55.3, 52.5, 47.8]

+2833142073 领取Python视频
在这里插入图片描述
在这里插入图片描述

最后

以上就是明亮机器猫最近收集整理的关于Python入门-循环技巧介绍的全部内容,更多相关Python入门-循环技巧介绍内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(95)

评论列表共有 0 条评论

立即
投稿
返回
顶部