Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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の関数として実行する

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

ishigero
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした