【发布时间】:2020-06-29 06:15:06
【问题描述】:
我想展平一个包含嵌套元素而不是嵌套元素的列表。从this 解决方案我已经尝试过,如果mylist 中的所有元素都是列表,它就可以工作,但是
在mylist 我有简单的文本字符串和嵌套列表。
我的清单是这样的:
mylist = [
'tz',
'7',
['a', 'b', 'c'],
[['2'], ['4', 'r'], ['34']],
[['7'], ['3', ['2', ['1']]], ['9']],
[['11',['7','w']], 'U1', ['0']]
]
我当前的代码是这样的,得到以下错误:
import collections#.abc
def flatten(l):
for el in l:
if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)):
yield from flatten(el)
else:
yield el
mylist1=[list(flatten(sublist)) if type(sublist) is list else sublist for sublist in mylist]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
File "<stdin>", line 3, in flatten
TypeError: isinstance() arg 2 must be a type or tuple of types
>>>
我的预期输出是这样的
mylist1 = [
'tz',
'7',
['a', 'b', 'c'],
['2', '4', 'r','34'],
['7','3','2','1','9'],
['11','7','w','U1','0']
]
缺少什么来解决这个问题?谢谢。
更新
现在,@Alok 建议的代码出现此错误
>>> for item in mylist:
... # if the item in mylist is a list, pass it to your flatten method else
... # add it to the final list
... if isinstance(item, list):
... final_list.append(list(flatten(item)))
... else:
... final_list.append(item)
...
Traceback (most recent call last):
File "<stdin>", line 5, in <module>
File "<stdin>", line 3, in flatten
TypeError: isinstance() arg 2 must be a type or tuple of types
【问题讨论】:
-
嘿,Ger,看看答案,让我知道这是否是您正在寻找的解决方案 :)