0
0

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 3 years have passed since last update.

二次元配列からキーごとの最大値を取り出す

Posted at

よくある話だとは思うのですが二次元配列

A = [
    ['001', '1'],
    ['001', '2'],
    ['002', '1'],
    ['002', '3'],
    ['001', '3'],
    ['002', '2'],
    ['002', '4']
]

こういうものから各要素の[0]をキーとして、キーごとの[1]の最大値を求めたい場合のロジックを考えます。
上記の場合だと、[['001', '3'], ['002', '4']]が導き出したい答えです。


# 二次元配列[[key, value], [key, value], ...]
input_list = [
    ['001', '1'],
    ['001', '2'],
    ['002', '1'],
    ['002', '3'],
    ['001', '3'],
    ['002', '2'],
    ['002', '4']
]

# 各要素のkeyを取得して重複削除
keys = list(set(i[0] for i in input_list))
tmp_dict = {}
for k in keys:
    # 要素のkeyが一致するvalueをリスト化
    v_l = list(set([i[1] if i[0] == k else 0 for i in input_list]))
    # key: valueの辞書型で保持
    tmp_dict.update({k: v_l})
print(tmp_dict)  # {'001': [0, '3', '1', '2'], '002': [0, '3', '4', '1', '2']}

output_list = []
for k in tmp_dict.keys():
    # 各keyが保持するvalueの最大値を取得しリスト化
    output_list.append([k, max(tmp_dict[k], key=int)])
print(output_list)  # [['001', '3'], ['002', '4']]

というわけでキーごとの最大値が求められました。

0
0
4

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?