我正在尝试编写一个名为flatten_list的函数,该函数将可能嵌套的列表作为输入,并返回一个包含输入列表所有元素的非嵌套列表。
我的代码:
def flatten_list(alist):
"""
>>> flatten_list([1,2,3])
[1, 2, 3]
>>> flatten_list([1, [2,3], [4, 5], 6])
[1, 2, 3, 4, 5, 6]
"""
flat_list = []
for element in alist:
flat_list += element
return flat_list
此代码适用于包含字符串的列表,但不适用于整数值。如何更改代码以使其适用于两者?
感谢
答案 0 :(得分:2)
通常,这将以递归方式完成,例如:
def flatten(input_, output=None):
if output is None:
output = []
if isinstance(input_, basestring):
output.append(input_)
else:
for item in input_:
try:
flatten(item, output)
except TypeError:
output.append(item)
return output
这适用于可迭代容器的任意组合(例如set
,list
,tuple
,dict
(仅限键))和内容(例如{{1} },int
,float
),使用常见的EAFP Python样式。请注意字符串的特定例外情况,您可能不希望将其解压缩!
一些用法示例:
str
非迭代作为直接参数会发生什么:
>>> flatten([1, [2, [3, [4, 5], 6], 7], 8])
[1, 2, 3, 4, 5, 6, 7, 8]
>>> flatten([1, "foo", ["bar", 2], 3])
[1, 'foo', 'bar', 2, 3]
>>> flatten([1, (2, 3), {4: 5}])
[1, 2, 3, 4]
>>> flatten("hello")
['hello']
答案 1 :(得分:0)
你可以这样做:
a = [1, [2,3], [4, 5], 6]
def flatten(l,result = []):
if isinstance(l, list):
for i in l:
flatten(i)
else:
result.append(l)
return result
>>> print flatten(a)
[1, 2, 3, 4, 5, 6]
这将适用于更深层次的嵌套级别:
>>> print flatten([1, [2, [3, 4]]])
[1, 2, 3, 4]
答案 2 :(得分:0)
使用collections.Iterable
from collections import Iterable
def flatten(items):
for elem in items:
if isinstance(elem,Iterable) and not isinstance(elem,str):
for sub_elem in flatten(elem):
yield sub_elem
else:
yield elem
In [15]: print list(flatten((1, (2,3), [4, 5],{10,11,12}, 6)))
[1, 2, 3, 4, 5, 10, 11, 12, 6]
In [16]: print list(flatten((1, (2,3), (4,5,6), 6)))
[1, 2, 3, 4, 5, 6, 6]
In [17]: print list(flatten([1, "foo", ["bar", 2], 3]))
[1, 'foo', 'bar', 2, 3]