【问题标题】:How can I remove list inside list? [duplicate]如何删除列表中的列表? [复制]
【发布时间】:2021-07-12 00:37:00
【问题描述】:

我有一个这样的列表[1, 2, 3, [4, 5, 6]]

如何删除列表中的[ 字符,以便获得[1, 2, 3, 4, 5, 6]

这是我目前的代码:

a = [1, 2, 3, [4, 5, 6]]
new_a = []
for item in a:
    if len(item) > 1:
        for sub_item in item:
            new_a.append(sub_item)
    else:
        new_a.append(item)
print(new_a)

然后我得到了这个错误:

TypeError: object of type 'int' has no len()

但是当我用len(a[3]) 得到内部列表的长度时,它返回3

我该如何解决这个问题?

【问题讨论】:

标签: python list


【解决方案1】:

你可以使用extend():

a = [1, 2, 3, [4, 5, 6]]
new_a = []
for item in a:
    try:
        len(item)
        new_a.extend(item)
    except:
        new_a.append(item)
print(new_a)

或者你可以使用type()来检查项目是否是列表:

a = [1, 2, 3, [4, 5, 6]]
new_a = []
for item in a:
    if type(item) == list:
        new_a.extend(item)
    else:
        new_a.append(item)
print(new_a)

【讨论】:

    【解决方案2】:

    你应该使用isinstance而不是使用len来检查某个东西是否是一个列表:

    a = [1, 2, 3, [4, 5, 6]]
    new_a = []
    for item in a:
        if isinstance(item, list):
            for subitem in item:
                new_a.append(subitem)
        else:
            new_a.append(item)
    

    查看@Always Sunny 的评论,了解更简单的方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-17
      • 1970-01-01
      • 1970-01-01
      • 2020-10-20
      相关资源
      最近更新 更多