如何优雅的处理python list问题

查看:89
本文介绍了如何优雅的处理python list问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

问题如下:
有一个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. 若维度增加, 应该如何处理?

请指教!谢谢各位了

解决方案

再搓个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']

这篇关于如何优雅的处理python list问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆