如何处理带有嵌套列表和字符串元素的列表?

How to handle list with nested lists and strings elements?

我想展平包含嵌套元素和非嵌套元素的列表。从 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

问题出在某些情况下,我将指出:

  1. Python 3.x is not following collections.Iterable anymore, you need to import the items from collections.abc and always do try-catch for any import error
try:
    from collections.abc import Iterable
except ImportError:
    from collections import Iterable 
  1. Not utilizing your flatten method appropriately, the method, returns the data, but you have to store it in the form of a list and append it to the final answer list YOUR SUB ARRAYS ONLY BE PASSED INTO THIS METHOD
data.append(list(flatten(item)))

最终解决方案:

try:
    from collections.abc import Iterable
except ImportError:
    from collections import Iterable 

mylist = [
    'tz',
    '7',
    ['a', 'b', 'c'], 
    [['2'], ['4', 'r'], ['34']], 
    [['7'], ['3',  ['2', ['1']]], ['9']], 
    [['11',['7','w']], 'U1', ['0']]
]

def flatten(l):
    for el in l:
        if isinstance(el, Iterable) and not isinstance(el, (str, bytes)):
            yield from flatten(el)
        else:
            yield el
            
final_list = []
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, type([])): final_list.append(list(flatten(item)))
    else: final_list.append(item)
    
print(final_list)

输出

['tz', '7', ['a', 'b', 'c'], ['2', '4', 'r', '34'], ['7', '3', '2', '1', '9'], ['11', '7', 'w', 'U1', '0']]

希望你能通过这种方式达到你想要的效果。