有如下的嵌套列表
x0 = [('tom','jerry','spike'),('micky','minnie','donald')]
现在要将其中的最底层元素取出,形成一个新的列表:
['tom', 'jerry', 'spike', 'micky', 'minnie', 'donald']
常规方法用双重for循环来取出,并逐个添加的新的列表中:
character0=[]
for i in x0:
for j in i:
character0.append(j)
print character0
输出:
['tom', 'jerry', 'spike', 'micky', 'minnie', 'donald']
现在可以用一种较为紧凑的形式来达到同样的效果:
character1=[]
character1 = [i for innertuple in x0 for i in innertuple]
print character1
输出:
['tom', 'jerry', 'spike', 'micky', 'minnie', 'donald']
如果嵌套结构再复杂一些:
x1=[([1,2,3],[4,5,6]),([4,5,6],[7,8,9])]
那么在循环中再加一层即可:
print [i for innertuple in x1 for innerlist in innertuple for i in innerlist ]
输出:
[1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9]
来源:CSDN
作者:fanggenyuxian
链接:https://blog.csdn.net/fanggenyuxian/article/details/77427176