pythonlist可以嵌套吗
python中的列表是可以嵌套的。将嵌套的list遍历并输出是很常见的需求。以下通过两种方法达到目的
defnested_list(list_raw,result):
foriteminlist_raw:
ifisinstance(item,list):
nested_list(item,result)
else:
result.append(item)
returnresult
defflatten_list(nested):
ifisinstance(nested,list):
forsublistinnested:
foriteminflatten_list(sublist):
yielditem
else:
yieldnested
defmain():
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方法则是采用生成器的方式,本质上也是递归的思路。
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可以嵌套吗,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python函数标注是什么
python函数标注是什么在参数的使用方法中,还有一种解包的情况是需要我们掌握的。比如,将列表或者字典的值转换为函数的参数,就需要用到参数解...详情>>
2023-11-14 14:13:35
python正负索引的使用
python正负索引的使用本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、说明使用正索引(从左至右)、负索引(从右至左)访问元素,时...详情>>
2023-11-14 13:45:04
python垃圾回收的机制过程
python垃圾回收的机制过程本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、步骤(1)收集所有容器对象(list,dict,tuple,customClas...详情>>
2023-11-14 13:05:15
pythontry语句的执行原理
pythontry语句的执行原理1、原理分析(1)执行try子句(try和except关键字之间的多行语句)。(2)如果没有异常发生,则跳过except子句并完成try语句...详情>>
2023-11-14 09:37:35热门推荐
技术干货






