知行编程网知行编程网  2022-10-27 10:00 知行编程网 隐藏边栏  605 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于python如何嵌套列表的相关知识,包括python嵌套列表生成,以及python列表中嵌套字典这些编程知识,希望对大家有参考作用。

python如何嵌套列表

python中的列表可以嵌套。遍历和输出嵌套列表是一种常见的需求。有两种方法可以实现这一点

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 方法使用递归方法。如果项目是列表类型,它会继续递归调用自身。如果没有,只需将项目添加到结果列表中。

flatten_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]

推荐学习《
》。

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享