Pythonの変数、コンテナ、真偽値、展開アサインの実践ガイド

変数・メモリ管理の再確認

Pythonで状態を表現する「変数」は「名前」と「値」のペアで構成される。名前は意味を持ち、英数字とアンダースコアのみ使用し数字で始めてはならない。定数は慣習的に変更しないものだが、実際には変更可能である。

値は参照カウントで管理され、0になるとガベージコレクションが解放する。起動時に[-5,256]の整数は固定アドレスで共有される小整数池が用意されている。

データ型の基礎

  • int: %(剰余)、//(切り捨て除算)、**(べき乗)が使える
  • float: 同様の演算子に対応
  • str: シングル・ダブル・トリプルクォートで囲み、str() int() float()で相互変換

アサインのテクニック

# 連鎖代入
x = y = z = 100

# 交換代入
a, b = 5, 9
a, b = b, a          # タプル展開でスワップ

リスト list

順序付きの複数要素を格納する可変シーケンス。

empty = []
chars = list("hello")   # ['h','e','l','l','o']
nums  = list(range(3))  # [0,1,2]

# インデックスアクセス
colors = ["red", "green", "blue"]
print(colors[-1])  # blue

辞書 dict

キーと値のペアでデータを管理し、キーによる高速検索が可能。

user = {"name": "taro", "age": 25, "active": True}

# キーで取得
print(user["name"])

# 複数レコード
people = [
    {"name": "hanako", "age": 30},
    {"name": "jiro",   "age": 22}
]
print(people[1]["name"])

真偽値 bool

条件判定の結果として得られるTrue / False

print(10 > 3)          # True
print(bool(""))        # False(空文字列)
print(bool([1, 2]))    # True(空でないリスト)

数値0、None、空コンテナ、空文字列はすべて偽と評価される。

アンパック(展開代入)

data = [10, 20, 30, 40, 50]

# 全要素を個別変数へ
first, second, third, fourth, fifth = data

# 不要部分を _ でスキップ
head, *_, tail = data   # head=10, tail=50, _=[20,30,40]

# タプルやリストの即時展開
x, y, z = 7, 8, 9

ユーザー入力とフォーマット出力

# 標準入力
reply = input("何か入力: ")  # 常にstr型

# f-string
name = "alice"
score = 95.678
print(f"{name}の得点は{score:.2f}")  # aliceの得点は95.68

# formatメソッド
print("{0} {1}".format("hello", "world"))
print("{:>10}".format("right"))  # 右寄せ10桁

タグ: Python List dict bool unpacking

7月14日 00:20 投稿