【问题标题】:How to handle list with nested lists and strings elements?如何处理带有嵌套列表和字符串元素的列表?
【发布时间】: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,看看答案,让我知道这是否是您正在寻找的解决方案 :)

标签: python-3.x nested-lists


【解决方案1】:

问题在于我将指出的一些实例:

  1. Python 3.x 不再关注collections.Iterable,您需要从collections.abc 导入项目,并始终为任何导入错误执行try-catch
try:
    from collections.abc import Iterable
except ImportError:
    from collections import Iterable 
  1. 未正确使用您的 flatten 方法,该方法返回数据,但您必须将其以列表的形式存储并将其附加到最终答案列表 您的子数组只能传递到此方法中
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']]

希望你可以通过这种方式实现你想要的输出。

【讨论】:

  • 您好 Alok,感谢您的帮助。我复制/粘贴了您的整个代码,但仍然出现错误。这次是我在原始帖子上所做的更新下方显示的错误。
  • 你使用的是哪个 python 版本的@GerCas?你能做到吗,让我知道这是否适合你:isinstance(names, type(list))isinstance(names, type([]))。另外,我已经测试了代码,它按预期工作。尽快让我知道,我们会在这方面为您提供帮助
  • 嗨@Alok,python 版本是 3.8.2。我已经尝试了这两个选项,并且只使用了这个 if isinstance(item, type([])): 非常感谢您的帮助。
  • 感谢您的来信。保持这种状态。通常,此站点上的 cmets 往往是粗鲁和缺乏个性的。
  • 嘿@GerCas,非常感谢您的称赞。我肯定会接受您的建议/称赞并继续前进。这是一个双向的事情,看,你从中学到了一些东西,我也从你那里学到了东西。谢谢那些话。 :)
猜你喜欢
  • 2019-08-21
  • 2021-10-21
  • 2016-02-08
  • 1970-01-01
  • 2021-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
相关资源
最近更新 更多