今さらPython3 (23) - For
第4章続行中。
- 作者: Bill Lubanovic,斎藤康毅,長尾高弘
- 出版社/メーカー: オライリージャパン
- 発売日: 2015/12/01
- メディア: 単行本(ソフトカバー)
- この商品を含むブログを見る
Forの使い方
>>> rabbits = ['Flopsy', 'Mopsy', 'Cottontail', 'Peter'] >>> current = 0 >>> while current < len(rabbits): ... print(rabbits[current]) ... current += 1 ... Flopsy Mopsy Cottontail Peter >>>
カウンタの変数を持たせてぐるぐる回すパターン。古典的だけど、昨日みたいにカウンタの初期化を忘れたり、カウントアップするロジックを忘れたりして、よくミスる。
>>> for rabbit in rabbits: ... print(rabbit) ... Flopsy Mopsy Cottontail Peter >>>
全件なめるという意味では、こっちの方がスマートだよね。
>>> word = 'cat' >>> for letter in word: ... print(letter) ... c a t >>>
文字列(str)に対してin演算子で回す場合は、1文字ずつ処理する。
>>> accusation = {'room': 'ballroom', 'weapon':'lead pipe', 'person': 'Col. Must ard'} >>> for card in accusation: # or, for card in accusation.keys(): ... print(card) ... room weapon person >>> for card in accusation.keys(): ... print(card) ... room weapon person
これは、辞書(dict)を使った場合、何も指定しない場合はkeyだけが処理される(keys()でも同じ)のに対し、値を出すときはitems()を使う。
>>> for item in accusation.items(): ... print(item) ... ('room', 'ballroom') ('weapon', 'lead pipe') ('person', 'Col. Mustard') >>> >>> for key, value in accusation.items(): ... print(key, value) ... room ballroom weapon lead pipe person Col. Mustard >>>
forのところの変数を1つにすると、タプル形式で吐いてくれる感じだね。値だけ処理したい場合は、forの後ろに2つ変数を置いてitems()を使い、キー用に用意した変数は無視する感じで実現できるはず。上の例なら、print(value)だけにすると。
>>> accusation = {'room':'ballroom', 'weapon':'lead pipe', 'person':'Col.Mustard'} >>> for value in accusation.values(): ... print(value) ... ballroom lead pipe Col.Mustard
そんなことない。values()が使える。
>>> for card, contents in accusation.items(): ... print('Card', card, 'has the contents', contents) ... Card room has the contents ballroom Card weapon has the contents lead pipe Card person has the contents Col. Mustard
一応、本に載っている例も試してみた。
elseも使える
>>> cheeses = [] >>> for cheese in cheeses: ... print('This shop has some lovely', cheese) ... break ... else: ... print('This is not much of a cheese shop, is it?') ... This is not much of a cheese shop, is it? >>> cheeses = ['mozzarella', 'gorgonzolla'] >>> for cheese in cheeses: ... print('This shop has some lovely', cheese) ... break ... else: ... print('This is not much of a cheese shop, is it?') ... This shop has some lovely mozzarella >>>
ゴルゴンゾーラはチーズじゃないらしい。ではなく、forで処理するものがなければ、elseに飛んでその処理を実行するというのはwhileと同じだね。
>>> cheeses = [] >>> found_one = False >>> for cheese in cheeses: ... found_one = True ... print('This shop has some lovely', cheese) ... break ... >>> if not found_one: ... print('This is not much of a cheese shop, is it?') ... This is not much of a cheese shop, is it?
ま、こうするより楽でしょという事ですね。あと、本文では省略されているけど、continueも使える模様。
(つづく)