當在字典中循環時,用 items()
方法可將關鍵字和對應的值同時取出html
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} >>> for k, v in knights.items(): ... print(k, v) ... gallahad the pure robin the brave
當在序列中循環時,用 enumerate()
函數能夠將索引位置和其對應的值同時取出python
>>> 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()
函數app
>>> for i in reversed(range(1, 10, 2)): ... print(i) ... 9 7 5 3 1
若是要按某個指定順序循環一個序列,能夠用 sorted()
函數,它能夠在不改動原序列的基礎上返回一個新的排好序的序列函數
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> for f in sorted(set(basket)): ... print(f) ... apple banana orange pear
有時可能會想在python循環時修改列表內容,通常來講改成建立一個新列表是比較簡單且安全的oop
>>> 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]