複数のリストを同時に処理 (zip / zip_longest)
Pythonでは複数のリストやタプルなどを同時に処理することができるzip関数、izip_longest関数があります(Python 3系では「zip_longest」です)。
下記の例では2つのリストを同じループで処理し、それぞれの要素を取得しています。
# -*- coding: utf-8 -*-
item_list = ['desktop', 'laptop', 'tablet', 'smartphone']
stock_list = [12, 83, 55, 0]
for item_name, stock_count in zip(item_list, stock_list):
print '{} / {}'.format(item_name, stock_count)
--実行結果--
desktop / 12 laptop / 83 tablet / 55 smartphone / 0
先の例ではそれぞれのリストは同じ要素数でした。要素数が異なる場合にzip関数で処理したらどうなるのでしょうか。
# -*- coding: utf-8 -*-
item_list = ['desktop', 'laptop', 'tablet', 'smartphone']
stock_list = [12, 83, 55]
for item_name, stock_count in zip(item_list, stock_list):
print '{} / {}'.format(item_name, stock_count)
--実行結果--
desktop / 12 laptop / 83 tablet / 55
実行結果のようにzip関数は要素数が少ない方に合わせて処理が終了します。izip_longest関数を用いると要素数が多い方に合わせて処理が行われます(Python 3系ではzip_longest関数を使用してください)。
Python 2系
# -*- coding: utf-8 -*-
import itertools
item_list = ['desktop', 'laptop', 'tablet', 'smartphone']
stock_list = [12, 83, 55]
for item_name, stock_count in itertools.izip_longest(item_list, stock_list):
print '{} / {}'.format(item_name, stock_count)
Python 3系
import itertools
item_list = ['desktop', 'laptop', 'tablet', 'smartphone']
stock_list = [12, 83, 55]
for item_name, stock_count in itertools.zip_longest(item_list, stock_list):
print('{} / {}'.format(item_name, stock_count))
--実行結果--
desktop / 12 laptop / 83 tablet / 55 smartphone / None
またfillvalueを指定するとNone以外の値で補われます。
Python 2系
# -*- coding: utf-8 -*-
import itertools
item_list = ['desktop', 'laptop', 'tablet', 'smartphone']
stock_list = [12, 83, 55]
for item_name, stock_count in itertools.izip_longest(item_list, stock_list, fillvalue='no stock'):
print '{} / {}'.format(item_name, stock_count)
--実行結果--
desktop / 12 laptop / 83 tablet / 55 smartphone / no stock
知っていると得します!
▶応用編:各要素の真偽判定 (all / any)
