LoginSignup
5
5

More than 5 years have passed since last update.

【備忘】Effective Python 1章(スライス、リスト内包表記、lambda)

Last updated at Posted at 2018-04-19

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

シーケンスのスライス

nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

print('first four:', nums[:4])      # first four: [0, 1, 2, 3]
print('last four:', nums[-4:])      # last four: [7, 8, 9, 10]
print('middle two:', nums[3:-3])    # middle two: [3, 4, 5, 6, 7]

print(nums[:])        # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(nums[:5])       # [0, 1, 2, 3, 4]
print(nums[:-1])      # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(nums[4:])       # [4, 5, 6, 7, 8, 9, 10]
print(nums[-3:])      # [8, 9, 10]
print(nums[2:5])      # [2, 3, 4]
print(nums[2:-1])     # [2, 3, 4, 5, 6, 7, 8, 9]
print(nums[-3:-1])    # [8, 9]

スッキリ書ける。

リスト内包表記とlambda

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

リスト内包表記

[x**2 for x in nums]
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

lambda

list(map(lambda x: x**2, nums))
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

条件式も使える

[x**2 for x in nums if x % 2 == 0] 
# [4, 16, 36, 64, 100]

filterを使いlambdaでも表現できる

list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, nums)))
# [4, 16, 36, 64, 100]

内包表記は辞書にも使える

chile_ranks = {'ghost': 1, 'habanero': 2, 'cayenne': 3}
{rank: name for name, rank in chile_ranks.items()}
# {1: 'ghost', 2: 'habanero', 3: 'cayenne'}

{len(name) for name in rank_dict.values()}
# {8, 5, 7}

lambdaは少し可読性が下がる。
内包表記はfor文より速い。
・appendメソッドの呼び出し部分のオーバーヘッド
・for文はループする度にリストオブジェクトのappendを参照する
・for文はappendをpythonの関数として実行する

速くて見やすいって最高。

5
5
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
5
5