LoginSignup
1
4

More than 5 years have passed since last update.

python n次元リストを1次元にする関数

Posted at
def flatten(lstnd):
    tmp = []
    def flattenlst(lst):
        for i in lst:
            if isinstance(i,list) or isinstance(i,set) or isinstance(i,tuple):
                flattenlst(i)
            else:
                tmp.append(i)
    flattenlst(lstnd)
    return tmp

再帰で深く入って行ってまっ平らにする。
内包表記でも書けるけど、こっちのほうが早いんじゃないかと思う。

a = [
 [[['衣服']], 'サイズ', [['XS']], None],
 [[['衣服']], 'サイズ', [['S']], None],
 [[['衣服']], 'サイズ', [['M']], None],
 [[['衣服']], 'サイズ', [['L']], None],
 [[['衣服']], 'サイズ', [['XL']], None]]
print(flatten(a))
>>>['衣服', 'サイズ', 'XXXS', None, '衣服', 'サイズ', 'XXS', None, '衣服',
 'サイズ', 'XS', None, '衣服', 'サイズ', 'S', None, '衣服', 'サイズ', 'M',
 None, '衣服', 'サイズ', 'L', None, '衣服', 'サイズ', 'LL', None, '衣服',
 'サイズ', 'XL', None, '衣服', 'サイズ', 'XXL', None, '衣服', 'サイズ',
 'XXXL', None, '衣服', 'サイズ', 'XXXXL', None]

1
4
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
1
4