python中list能不能嵌套
小编给大家分享一下python中list能不能嵌套,相信大部分人都还不怎么了解,因此分享这篇文章给大家学习,希望大家阅读完这篇文章后大所收获,下面让我们一起去学习方法吧!
python中的列表是可以嵌套的。将嵌套的list遍历并输出是很常见的需求。以下通过两种方法达到目的
defnested_list(list_raw,result):foriteminlist_raw:ifisinstance(item,list):nested_list(item,result)else:result.append(item)returnresultdefflatten_list(nested):ifisinstance(nested,list):forsublistinnested:foriteminflatten_list(sublist):yielditemelse:yieldnesteddefmain():list_raw=["a",["b","c",["d"]]]result=[]print"nested_listis:",nested_list(list_raw,result)print"flatten_listis:",list(flatten_list(list_raw))main()
让代码run起来,输出为:
nested_listis:['a','b','c','d']flatten_listis:['a','b','c','d']
nested_list方法采用递归的方式,如果item是list类型,继续递归调用自身。如果不是,将item加入结果列表中即可。
flatten_list方法则是采用生成器的方式,本质上也是递归的思路。
推荐学习《python教程》
2.两层嵌套list去重
list里面套了一层list,需要去重,并在生成一个去重的list。请看代码:
defdup_remove_set(list_raw):result=set()forsublistinlist_raw:item=set(sublist)result=result.union(item)returnlist(result)defmain():list_dup=[[1,2,3],[1,2,4,5],[5,6,7]]printdup_remove_set(list_dup)
让代码run起来:
[1,2,3,4,5,6,7]
基本思路:将每一个子list转为set,然后求并集,即可。
3.多重嵌套去重
defdup_remove(list_raw,result):foriteminlist_raw:ifisinstance(item,list):dup_remove(item,result)else:result.add(item)returnlist(result)defmain():list_raw=["a",["b","c",["d","a","b"]]]result=set()print"dup_removeis:",dup_remove(list_raw,result)
让代码run起来:
dup_removeis:['a','c','b','d']
基本思路与之前遍历嵌套list的思路差不多,唯一的区别就是之前result是一个list,而要去重的话用result是一个set,保证最后的结果为去重的结果。
以上是python中list能不能嵌套的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。