通常,这将以递归方式进行,例如:
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(仅按键))和内容(例如
int,
float,
str),使用普通EAFP Python的风格。注意字符串的特定异常,您可能不想将其解压缩!
一些用法示例:
>>> 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']
非可迭代对象作为直接参数会发生什么:
>>> flatten(1)Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> flatten(1) File "<pyshell#1>", line 4, in flatten for item in input_:TypeError: 'int' object is not iterable
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)