Python循环作为最基础的流程控制语句在python开发的过程中会经常需要用到,那么在使用循环的时候有没有什么技巧可以更好的帮助开发呢。下面小编就介绍六个常用的循环技巧,一起往下看看吧。

python 循环输入try python中怎么循环输入_python 循环输入try

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

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

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

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

3.同时循环两个或多个序列时,用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))

4.逆向循环序列时,先正向定位序列,然后调用reversed()函数:

>>> for i in reversed(range(1, 10, 2)):
...     print(i)

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

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

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

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

以上六个就是python中常用的六个循环技巧了,如果对你有帮助的话记得点赞分享一下哦。