Python循环的技巧介绍(附代码)
本篇文章给大家带来的内容是关于python循环的技巧介绍(附代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
当在字典中循环时,用 items() 方法可将关键字和对应的值同时取出
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}>>> for k, v in knights.items():... print(k, v)...gallahad the purerobin the brave
当在序列中循环时,用 enumerate() 函数可以将索引位置和其对应的值同时取出
>>> for i, v in enumerate(['tic', 'tac', 'toe']):... print(i, v)...0 tic1 tac2 toe
当同时在两个或更多序列中循环时,可以用 zip() 函数将其内元素一一匹配。
立即学习“Python免费学习笔记(深入)”;
>>> 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)...73
如果要按某个指定顺序循环一个序列,可以用 sorted() 函数,它可以在不改动原序列的基础上返回一个新的排好序的序列
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']>>> for f in sorted(set(basket)):... print(f)...applebananaorangepear
有时可能会想在python循环时修改列表内容,一般来说改为创建一个新列表是比较简单且安全的
>>> 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]
【