如何优雅的处理python list问题

阿ddd
  • 167

问题如下:
有一个list, 是有list嵌套与Str的混合的list, 如何能优雅的处理成一个简单的list

# example:
tmp = ['0-0', ['0-1-0', '0-1-5'], ['0-2-0', '0-2-1', '0-2-2'], ['3-1-0', '3-1-1', '3-1-2', '3-1-3', '3-1-4', '3-1-5'], '4-0', '4-1', '5-0', '5-1']
# to:
des = ['0-0', '0-1-0', '0-1-5', '0-2-0', '0-2-1', '0-2-2', '3-1-0', '3-1-1', '3-1-2', '3-1-3', '3-1-4', '3-1-5', '4-0', '4-1', '5-0', '5-1']

有一些要求:

  1. 实际问题是很大量的数, 如何不增加额外list的情况下处理? (需要内存控制)

  2. 维度已知, 二维

  3. 若维度增加, 应该如何处理?

请指教!谢谢各位了

回复
阅读 2.7k
4 个回答
✓ 已被采纳

再搓个generator的, 这下不会引入额外的list了, 另外内存占用应该也比之前写的递归理论上优化不少~
py3.x

import collections


def list_exp1(iterable):
    for el in iterable:
        if not isinstance(el, str) and isinstance(el, collections.Iterable):
            yield from list_exp(el)
        else:
            yield el

py2.x

import collections


def list_exp1(iterable):
    for el in iterable:
        if not isinstance(el, basestring) and isinstance(el, collections.Iterable):
            for subel in el:
                yield subel
        else:
            yield el

手搓了个递归, 支持任意维度

def list_exp(lst):
    _lst = []
    for i in lst:
        if not isinstance(i, list):
            _lst.append(i)
        else:
            _lst += list_exp(i)
    return _lst

测试结果

# 二维
tmp = ['0-0', ['0-1-0', '0-1-5'], ['0-2-0', '0-2-1', '0-2-2'], ['3-1-0', '3-1-1', '3-1-2', '3-1-3', '3-1-4', '3-1-5'], '4-0', '4-1', '5-0', '5-1']
print(list_exp(tmp))
['0-0', '0-1-0', '0-1-5', '0-2-0', '0-2-1', '0-2-2', '3-1-0', '3-1-1', '3-1-2', '3-1-3', '3-1-4', '3-1-5', '4-0', '4-1', '5-0', '5-1']

# N维
tmp = ['0-0', ['0-1-0', '0-1-5', ['0-1-0', '0-1-5'], ['0-0', ['0-1-0', '0-1-5', ['0-1-0', '0-1-5']]]]]
print(list_exp(tmp))
['0-0', '0-1-0', '0-1-5', '0-1-0', '0-1-5', '0-0', '0-1-0', '0-1-5', '0-1-0', '0-1-5']
from compiler.ast import flatten

des = flatten(tmp)

支持多维。
你也可以自己写个递归函数,自己处理。

yenkey
  • 3
新手上路,请多包涵

python3

>>> tmp = ['0-0', ['0-1-0', '0-1-5'], ['0-2-0', '0-2-1', '0-2-2'], ['3-1-0', '3-1-1', '3-1-2', '3-1-3', '3-1-4', '3-1-5'], '4-0', '4-1', '5-0', '5-1']
>>> str(tmp).translate(''.maketrans('',''," '[]")).split(',')
['0-0', '0-1-0', '0-1-5', '0-2-0', '0-2-1', '0-2-2', '3-1-0', '3-1-1', '3-1-2', '3-1-3', '3-1-4', '3-1-5', '4-0', '4-1', '5-0', '5-1']
你知道吗?

宣传栏