python嵌套列表的方法

发布时间:2020-08-01 10:48:06 作者:清晨
来源:亿速云 阅读:413

不懂python嵌套列表的方法?其实想解决这个问题也不难,下面让小编带着大家一起学习怎么去解决,希望大家阅读完这篇文章后大所收获。

python中的列表是可以嵌套的。将嵌套的list遍历并输出是很常见的需求。以下通过两种方法达到目的

def nested_list(list_raw,result):
    for item in list_raw:
        if isinstance(item, list):
            nested_list(item,result)
        else:
            result.append(item)
    return  result   
def flatten_list(nested):
    if isinstance(nested, list):
        for sublist in nested:
            for item in flatten_list(sublist):
                yield item
    else:
        yield nested
def main():   
    list_raw = ["a",["b","c",["d"]]]
    result = []
    print "nested_list is:  ",nested_list(list_raw,result)
    print "flatten_list is: ",list(flatten_list(list_raw))
main()

运行,输出为:

nested_list is:   ['a', 'b', 'c', 'd']
flatten_list is:  ['a', 'b', 'c', 'd']

nested_list方法采用递归的方式,如果item是list类型,继续递归调用自身。如果不是,将item加入结果列表中即可。

flatten_list方法则是采用生成器的方式,本质上也是递归的思路。

两层嵌套list去重

list里面套了一层list,需要去重,并在生成一个去重的list。请看代码:

def dup_remove_set(list_raw):
    result = set()
    for sublist in list_raw:
        item = set(sublist)
        result = result.union(item)
    return list(result)
def main():  
    list_dup = [[1,2,3],[1,2,4,5],[5,6,7]]
    print dup_remove_set(list_dup)

运行

[1, 2, 3, 4, 5, 6, 7]

感谢你能够认真阅读完这篇文章,希望小编分享python嵌套列表的方法内容对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,遇到问题就找亿速云,详细的解决方法等着你来学习!

推荐阅读:
  1. Python-嵌套列表的推导式
  2. 嵌套列表转换为单列表

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:在django中运行scrapy框架的方法

下一篇:TensorFlow如何实现批量归一化

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》