我有一个对象列表,其中对象可以是列表或标量。我想要一个只有标量的扁平列表。 例如:
L = [35,53,[525,6743],64,63,[743,754,757]]
outputList = [35,53,525,6743,64,63,743,754,757]
P.S。此问题的答案不适用于异构列表。 Flattening a shallow list in Python
答案 0 :(得分:8)
这是一个相对简单的递归版本,它将展平列表的任何深度
l = [35,53,[525,6743],64,63,[743,754,757]]
def flatten(xs):
result = []
if isinstance(xs, (list, tuple)):
for x in xs:
result.extend(flatten(x))
else:
result.append(xs)
return result
print flatten(l)
答案 1 :(得分:4)
可以使用numpy
import numpy as np
np.hstack(l)
你最终得到了一个ndarray
array([ 35, 53, 525, 6743, 64, 63, 743, 754, 757])
答案 2 :(得分:4)
>>> data = [35,53,[525,6743],64,63,[743,754,757]]
>>> def flatten(L):
for item in L:
if isinstance(item,list):
for subitem in item:
yield subitem
else:
yield item
>>> list(flatten(data))
[35, 53, 525, 6743, 64, 63, 743, 754, 757]
以下是用于代码 - 高尔夫目的的单行版本(看起来不太好:D)
>>> [y for x in data for y in (x if isinstance(x,list) else [x])]
[35, 53, 525, 6743, 64, 63, 743, 754, 757]
答案 3 :(得分:3)
l = [35,53,[525,6743],64,63,[743,754,757]]
outputList = []
for i in l:
if isinstance(i, list):
outputList.extend(i)
else:
outputList.append(i)
答案 4 :(得分:1)
这是一个oneliner,基于the question you've mentioned:
list(itertools.chain(*((sl if isinstance(sl, list) else [sl]) for sl in l)))
更新:以及完全基于迭代器的版本:
from itertools import imap, chain
list(chain.from_iterable(imap(lambda x: x if isinstance(x, list) else [x], l)))
答案 5 :(得分:1)
outputList = []
for e in l:
if type(e) == list:
outputList += e
else:
outputList.append(e)
>>> outputList
[35, 53, 525, 6743, 64, 63, 743, 754, 757]
答案 6 :(得分:0)
def nchain(iterable):
for elem in iterable:
if type(elem) is list:
for elem2 in elem:
yield elem2
else:
yield elem
答案 7 :(得分:0)
允许无限树深度的递归函数:
def flatten(l):
if isinstance(l,(list,tuple)):
if len(l):
return flatten(l[0]) + flatten(l[1:])
return []
else:
return [l]
>>>flatten([35,53,[525,[1,2],6743],64,63,[743,754,757]])
[35, 53, 525, 1, 2, 6743, 64, 63, 743, 754, 757]
我试图避免使用isinstance来允许泛型类型,但旧版本会对字符串进行无限循环。现在它正确地平整字符串(现在不是字符,但好像它假装一个字符串是一个标量)。
答案 8 :(得分:0)
>>> L = [35,53,[525,6743],64,63,[743,754,757]]
>>> K = []
>>> [K.extend([i]) if type(i) == int else K.extend(i) for i in L ]
[None, None, None, None, None, None]
>>> K
[35, 53, 525, 6743, 64, 63, 743, 754, 757]
答案 9 :(得分:0)
此解决方案仅适用于您的特定情况(列表中的标量)并假设标量为整数。这是一个可怕的解决方案,但它非常短暂。
outputlist = map(int,",".split(str(L).replace("[","").replace("]","")))
答案 10 :(得分:0)
答案很简单。利用递归。
def flatten(nst_lst, final_list):
for val in nst_lst:
if isinstance(val, list):
flatten(val, final_list)
else:
final_list.append(val)
return final_list
#Sample usage
fl_list = []
lst_to_flatten = [["this",["a",["thing"],"a"],"is"],["a","easy"]]
print(flatten(lst_to_flatten, fl_list))