LoginSignup
11
11

More than 5 years have passed since last update.

Python 多次元配列

Posted at

多次元配列を使うのに、いちいちリスト内包表記で書くのは面倒だし、可読性が悪い

def mlist(n, *args, **keys):
    if len(args) == 0:
        return [keys.get('default')] * n
    else:
        return [mlist(*args, **keys) for i in range(n)]

print mlist(5)
# [None, None, None, None, None]

print mlist(2, 3, default='a')
# [['a', 'a', 'a'], ['a', 'a', 'a']]

print mlist(4, 3, 2, default=1)
# [[[1, 1], [1, 1], [1, 1]], [[1, 1], [1, 1], [1, 1]], [[1, 1], [1, 1], [1, 1]], [[1, 1], [1, 1], [1, 1]]]
11
11
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
11
11