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

ハマりメモ: 2次元配列の値のmaxを取るときにmax(max(list))はしてはならない

Last updated at Posted at 2020-01-12
a = []
a.append([-1,-1,-1])
a.append([-1, 2, -1])
a.append([-1, -1, 3])

というリストがあった際に、このリストの中の最大値3を得たい。つまり、

>>> max(list(map(lambda x: max(x), a)))
3

を行いたい。この際にmaxを入れ子にするとうまくいかない。

>>> max(max(a))
2

これは、max(a)をした際に[-1,-1,-1][-1, 2, -1][-1, -1, 3]の比較が行われる。これは辞書順に比較され、

>>> [-1, 2, -1] > [-1, -1, 3]
True
>>> "acb" > "abz" # これと一緒
True

となるためである。

解法1: map

>>> max(list(map(lambda x: max(x), a)))
3

解法2: itertools.chainでflatなlistにする

>>> from itertools import chain
>>> list(chain(*a))
[-1, -1, -1, -1, 2, -1, -1, -1, 3]
>>> max(chain(*a))
3
9
3
1

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
9
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?