# 1 分解嵌套列表, 列表的遍历
m = ["a", ["b", "c", ["inner"]]]
for i in m:
if isinstance(i, list):
for j in i:
print(j)
else:
print(i)
# 2 分解嵌套列表 如何将一个列表嵌套的结构中的每个最底层元素取出,并形成一个新的列表
x1 = [('tom', 'jerry', 'spike'), ('micky', 'minnie', 'donald')]
character0 = []
for i in x1:
for j in i:
character0.append(j)
print("方法1:", character0)
# 方法1: ['tom', 'jerry', 'spike', 'micky', 'minnie', 'donald']
x2 = [('tom', 'jerry', 'spike'), ('micky', 'minnie', 'donald')]
character1 = []
character1 = [i for innertuple in x2 for i in innertuple] # 用列表生成式
print("方法2:", character1)
# 方法2: ['tom', 'jerry', 'spike', 'micky', 'minnie', 'donald']
x3 = [([1, 2, 3], [4, 5, 6]), ([4, 5, 6], [7, 8, 9])]
character2 = []
character2 = [i for innertuple in x3 for innerlist in innertuple for i in innerlist] # 用列表生成式
print("方法3:", character2)
# 方法3: [1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9]
# 多重嵌套列表: list1 = [ 1, [2, 3], 4, [5, 6, 7]],取出每一个单个的元素 使用递归的方法解决
# 使用递归的方法解决
#x4 = [1, [2, 3], 4, [5, 6, 7]]
x4 = [1, [2, 3], 4, (5, 6, 7)]
character4 = []
def flat(nums):
res = []
for i in nums:
if isinstance(i, list) or isinstance(i, tuple):
res.extend(flat(i)) # 使用递归的方法解决
else:
res.append(i)
return res
print("方法4: ", flat(x4))
# 方法4: [1, 2, 3, 4, 5, 6, 7]