4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

競プロのためのPythonの便利な機能

Last updated at Posted at 2022-11-29

条件式 (Conditional Expressions)

expression1 if condition else expression2

conditionがTrueであればexpression1に評価され、
Falseであればexpression2に評価される。
JavaとC++の三項演算子 condition ? expression1 : expression2 に該当する。

伝統的なIF文で表現する場合:

if n >= 0:
    param = n
else:
    param = -n

条件式の場合:

param = n if n >= 0 else -n

条件式はソースコードの可読性を向上させる場合のみ使用する。

内包表記文法 (Comprehension Syntax)

リスト内包表記:

[expression for value in iterable if condition]

使用例:

n = 10
squares = [k * k for k in range(1, n + 1)]
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
factors = [k for k in range(1, n + 1) if n % k == 0]
# [1, 2, 5, 10]

リスト型以外に、集合型、ジェネレータ型、辞書型も内包表記をサポートする。

# list
[k * k for k in range(1, n + 1)]
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# set
{k * k for k in range(1, n + 1)}
# {64, 1, 4, 36, 100, 9, 16, 49, 81, 25}

# generator
(k * k for k in range(1, n + 1))
# generator object

# dictionary
{k : k * k for k in range(1, n + 1)}
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}

パッキングとアンパッキング (Packing and Unpacking)

tuple型にパッキングする例:

data = 2, 4, 6, 8
# (2, 4, 6, 8)

return x, y
# (x, y)

アンパッキングの例:

# unpacking
a, b, c, d = range(7, 11)

quotient, remainder = divmod(a, b)

for x, y in [ (1, 2), (3, 4), (5, 6) ]:

for k, v in data.items():

多重代入 (Simultaneous Assignments)の例:

x, y, z = 3, 4, 5

a, b = b, a + b

便利なライブラリ

collections.Counter()

a = ['a', 'b', 'c', 'd', 'a', 'a', 'b']
c = collections.Counter(a)
# Counter({'a': 3, 'b': 2, 'c': 1, 'd': 1})

考える価値がある手法

  • 番人を立てる
    * リストの前後に0を追加する
4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?