问题描述
对于NLP应用程序,我有一个列表列表,其中包含许多级别,我希望将它们全部展平并提取到一个列表中。这等效于R编程语言中的unlist
。堆栈溢出中的大多数代码只允许将列表向下平整一到两个级别。谁能帮助我做到这一点?
x = [1,2,[3,[4,5,21,[32,12]]]]
至
x = [1,3,4,32,12]
解决方法
这在python中是一个很大的问题,因为R中没有等效于unlist
函数的函数。为了能够将一个列表中的多级列表提取到一个列表中,该列表也称为flattening of a list
。
关于堆栈溢出的大多数问题都不能回答这个问题:
How to make a flat list out of list of lists?
我在这里介绍了一些python代码,它们使用简单的递归概念来实现此目的:
def unlist(m):
q = []
for x in m:
if (type(x) is list):
for y in x:
q.append(y)
continue
q.append(x)
for i in range(len(q)):
if (type(q[i]) is not list):
if (i == (len(q)-1)):
return q
continue
else:
break
for elem in q:
if (type(elem) is list):
z = unlist(elem)
q.remove(elem)
for item in z:
q.append(item)
return q
这会将列表内含列表的任何级别展平为单个列表。
x = [1,2,[3,[4,5,21,[32,12]]]]
至x = [1,3,4,32,12]
。