[Pythonの]ルーピングテクニック/ヒントサイクル

https://docs.python.org/zh-cn/3/tutorial/datastructures.html#tut-loopidioms

 

辞書内を循環するときに  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 

2以上の配列内を循環しながら、ときに、あなたはできる  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. 

次いで、配列の逆サイクル、正の第1標的配列とは、呼び出したとき  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 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]

おすすめ

転載: www.cnblogs.com/alfredsun/p/10978725.html