Home > Backend Development > Python Tutorial > Python-嵌套列表list的全面解析

Python-嵌套列表list的全面解析

WBOY
Release: 2016-06-16 08:47:59
Original
1206 people have browsed it

一个3层嵌套列表m

m=["a",["b","c",["inner"]]]

需要解析为基本的数据项a,b,c,inner

基本的取数据项方法:

for i in m:

print i这个只能取出第一层的a,和一个2层的嵌套列表["b","c",["inner"]]

结合内置函数和判断可以继续解析这个2层列表

for i in m:
	if isinstance(i,list):
		for j in i:
			print j
	else: print i结果

a
b
c
['inner']
Copy after login

这个2层嵌套也分开了了,但里面的列表没有分拆,虽然可以继续拆解得到结果,但非最佳选择

构造函数,迭代解析这个多层嵌套列表

 def printm(listin):
	for i in listin:
		if isinstance(i,list):
			printm(i)
		else: print i使用该函数直接解析嵌套列表,一次拆完

printm(m)
Copy after login

结果如下:

a
b
c
inner
Copy after login

以上这篇Python-嵌套列表list的全面解析就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template