Python 多次元配列

  • 11
    Like
  • 0
    Comment
More than 1 year has passed since last update.

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

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]]]