• 技术文章 >常见问题 >Python常见问题

    python如何嵌套列表

    silencementsilencement2019-12-18 09:52:52原创4738

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

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    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()

    运行,输出为:

    1

    2

    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。请看代码:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    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

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

    推荐学习《python教程》。

    专题推荐:列表
    上一篇:python的for循环如何实现 下一篇:python怎么下载第三方库

    相关文章推荐

    • python怎么获取列表元素的索引• python数组和列表区别是什么• python该如何打印列表

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网