python中循环的技巧

简介: 循环的技巧在字典中循环时,用 items() 方法可同时取出键和对应的值:

循环的技巧

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

>>>

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
...     print(k, v)
...
gallahad the pure
robin the brave

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

>>>

>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print(i, v)
...
0 tic
1 tac
2 toe

同时循环两个或多个序列时,用 zip() 函数可以将其内的元素一一匹配:

>>>

>>> 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() 函数:

>>>

>>> for i in reversed(range(1, 10, 2)):
...     print(i)
...
9
7
5
3
1

按指定顺序循环序列,可以用 sorted() 函数,在不改动原序列的基础上,返回一个重新的序列:

>>>

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for i in sorted(basket):
...     print(i)
...
apple
apple
banana
orange
orange
pear

使用 set() 去除序列中的重复元素。使用 sorted()set() 则按排序后的顺序,循环遍历序列中的唯一元素:

>>>

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...     print(f)
...
apple
banana
orange
pear

一般来说,在循环中修改列表的内容时,创建新列表比较简单,且安全:

>>>

>>> 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]
相关文章
|
2月前
|
Python
Python 学习之路 03 之循环
03-运行时数据区概述及线程
34 0
|
2月前
|
Python
python用户输入和while循环(四)
python用户输入和while循环(四)
28 1
|
1月前
|
程序员 Python
Python控制结构:条件语句和循环详解
【4月更文挑战第8天】本文介绍了Python的两种主要控制结构——条件语句和循环。条件语句包括`if`、`elif`和`else`,用于根据条件执行不同代码块。`if`检查条件,`else`提供替代路径,`elif`用于多个条件检查。循环结构有`for`和`while`,前者常用于遍历序列,后者在满足特定条件时持续执行。`for`可结合`range()`生成数字序列。`while`循环适用于未知循环次数的情况。循环控制语句`break`和`continue`能改变循环执行流程。理解和熟练运用这些控制结构是Python编程的基础。
|
2月前
|
存储 索引 Python
python用户输入和while循环(五)
python用户输入和while循环(五)
18 0
|
2月前
|
Python
python用户输入和while循环(三)
python用户输入和while循环(三)
20 0
|
2月前
|
存储 算法 索引
python用户输入和while循环(六)
python用户输入和while循环(六)
20 0
|
2月前
|
存储 索引 Python
python用户输入和while循环(七)
python用户输入和while循环(七)
17 0
|
5天前
|
机器学习/深度学习 JSON 数据库
Python每循环一次保存一次结果
Python每循环一次保存一次结果
9 1
|
12天前
|
Python 容器
Python中的for循环用法详解,一文搞定它
Python中的for循环用法详解,一文搞定它
|
12天前
|
Python
Python中的while循环,知其然知其所以然
Python中的while循环,知其然知其所以然