0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonのコンテナ系の書き方(備忘録)

Last updated at Posted at 2019-10-25

Pythonのコンテナ系の書き方(備忘録)

いつも書き方を忘れて探し回るのでメモっとく

リスト

a = []  # 空リスト
a = list()  # 空リスト
a = ['a', 'b', 'c']  # 値指定で定義
a = [0] * 10  # 値0を10個持つリスト
a = [[0] * 3 for i in range(2)]  # [[0,0,0], [0,0,0]]
a.append('d')  # 末尾に追加
a.insert(0, 'aaa')  # 先頭に追加。0を変えて任意の位置
a[0]  # 参照(範囲外でexception
a[0] = 'e'  # 上書き
a.pop()  # 末尾の要素を除去、値を返す(空リストだとエラー
a.pop(0)  # 先頭の要素を除去、値を返す(空リストだとエラー
'b' in a  # 'b'が存在すればTrue、無ければFalse
'c' not in a  # 'c'が存在すればFalse、無ければTrue
a.index('b')  # 'b'の位置を返す。なければエラー
len(a)  # 要素の個数

リスト内リストの扱い方

a = [[1,2,3], [4,5,6], [7,8,9]]  # リスト内リストを定義
list(map(sum, a))  # 内部のリストについてそれぞれsumしたリスト
>> [6, 15, 24]
list(zip(*a))  # 縦横逆にしてリスト内タプル
>> [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
list(map(list, zip(*a)))  # 縦横逆にしてリスト内リスト
>> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
list(map(sum, zip(*a)))  # 縦横逆にして内側のリストの和のリスト
>> [12, 15, 18]

タプル

イミュータブル(値の追加、変更は不可)

a = ()  # 空タプル
a = tuple()  # 空タプル
a = ('a', 'b', 'c')  # 値指定で定義
a = ('d',)  # 要素が一つだけの場合、最後にカンマ付ける
a[0]  # 参照(範囲外でexception
'b' in a  # 'b'が存在すればTrue、無ければFalse
'c' not in a  # 'c'が存在すればFalse、無ければTrue
len(a)  # 要素の個数

辞書

バリューからキーを直接には取り出せない。順番は保持されない

a = {}  # 空辞書
a = dict()  # 空辞書
a = {'a': '', 'b': '', 'c': ''}  # 値指定で定義
a['d'] = ''  # キー&バリュー追加
a['b']  # キーで参照(存在しないキーだとエラー
a.get('z')  # キーで参照(存在しないキーでもエラーにならない
a['c'] = 'ううう'  # 上書き
del a['d']  # 削除
a.keys()  # キーの一覧
'b' in a  # キー'b'が存在すればTrue、無ければFalse
'c' not in a  # キー'c'が存在すればFalse、無ければTrue
len(a)  # 要素の個数

辞書のリスト

c = [{'id': 1, 'name': 'a'}, {'id': 2, 'name': 'b'}, {'id': 3, 'name': 'c'}]  # 定義
[x.get('name') for x in l]  # 特定のキーのリストを取得
# >> ['a', 'b', 'c']
[x.get('name', '---') for x in l]  # デフォルト値はgetで指定
[x.get('name') for x in l].index('b')  # あるキーの値から元のリストの位置を取得する
# >> 1

deque

キュー、スタック。リストより早い

from collections import deque
a = deque()  # 宣言
a.append('z')  # 末尾に追加
a.appendleft('a')  # 先頭に追加
a.pop()  # 末尾を削除、値を返す
a.popleft()  # 先頭を削除、値を返す
len(a)  # 要素の個数

heap

リスト型をヒープとして使うライブラリ。min-heapでインデックスは0始まり

import heapq
a = []  # 値はリスト型として持つ
heappush(a, 1)  # ヒープaに値1を追加
heappop(a)  # 最小値を返す

ヒープソートの実装例(公式に載ってる)

def heapsort(iterable):
    h = []
    for value in iterable:
        heappush(h, value)
    return [heappop(h) for i in range(len(h))]
heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?