LoginSignup
0
3

More than 5 years have passed since last update.

【備忘】Effective Python 1章(ジェネレータ、enumerate、例外)

Posted at

Pythonicな箇所をピックアップして残そうと思います。
これからPythonを勉強しようと思っている方にも役立つかもしれないです。

ジェネレータ

リスト内包表記では要素の全てをメモリに乗せるため、大量データを扱うときはジェネレータの方が良い。

書き方:リスト内包表記での[ ]を( )にする

words = ['hoge', 'fug', 'oo', 'i']
it = (len(word) for word in words)
print(it)           # <generator object <genexpr> at 0x7fa8dda48f10>
print(next(it))     # 4

ジェネレータは組み合わせて使うこともできる。(速い)

it_2 = ((x, x*2) for x in it)
print(it_2)           # <generator object <genexpr> at 0x7fa8dda48048>
print(next(it_2))     # (3, 6)
print(next(it_2))     # (2, 4)

enumerate

リストの反復処理で添字が必要なときに便利。

colors = ['white', 'blue', 'green', 'red']

rangeを使った場合

for i in range(len(colors)):
    color = colors[i]
    print('%d: %s is beautiful' % (i, color))

enumerateを使った場合

for i, color in enumerate(colors):
    print('%d: %s is beautiful' % (i, color))

結果

# 0: white is beautiful
# 1: blue is beautiful
# 2: green is beautiful
# 3: red is beautiful

例外

コードから


def main():
  normal_sample()
  print('////////////')
  exception_sample()

# try
# no problem
# finish
# ////////////
# exception
# finish


def exception_sample():
  try:
    open('/hoge.txt')

  except:
    print('exception') 

  else:
    print('no problem')

  finally:
    print('finish')


def normal_sample():
  try:
    print('try')

  except:
    print('exception') 

  else:
    print('no problem')

  finally:
    print('finish')


if __name__ == '__main__':
  main()

else

tryの中で例外が発生しなかった時に実行される

finally

tryの中で例外が発生しても、発生しなくても実行される

分かりやすい。

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3