从嵌套列表中删除元素

时间:2019-01-14 03:05:32

标签: python python-3.x

我是python的新手,正在学习有关列表的知识。我正在尝试创建一个将从列表中删除特定值的函数。我知道有一个.remove()函数可删除元素,但不适用于嵌套列表。

def remove(list, x):
   if x in list:  
      return list.remove(x)

mylist = [[1, 2, 3, 2, 4, 8, 2],2] 
remove(mylist, 2) 
print(mylist)

我想要得到的结果:

[1, 3, 4, 8]

提前感谢您的帮助

2 个答案:

答案 0 :(得分:4)

我在这里自定义代码,您可以看到在线版本https://onlinegdb.com/Sk2oA9KGV

如果您不理解,请继续阅读说明

def remove(list, x):
       if x in list:  
          return list.remove(x)

    mylist = [[1, 2, 3, 2, 4, 8, 2],2]
    for i in range(len(mylist)):

        if isinstance(mylist[i], list) == True : 
            mylist[i] = list(set(mylist[i]))
            mylist[i].remove(2)
            mylist[i].sort()
        else : 
            if mylist[i] == 2 : 
                del mylist[i]
    print(mylist)
    print()

最终结果是这样的

print(mylist)
  

[[1、3、4、8]]

print(mylist[0])
  

[1、3、4、8]


  

完整的说明

首先,您需要使用for循环将多维数组中的数组分开

for i in range(len(mylist)):

然后,您应该检查当前拥有的变量是否为array

if isinstance(mylist[i], list) == True :

如果条件为True,则继续 要在此处2删除重复的项目,您需要在这一行

mylist[i] = list(set(mylist[i]))

然后运行删除功能

mylist[i].remove(2)

此后,您的结果将像这样[8, 1, 3, 4] 然后您应该按此代码对数组进行排序

mylist[i].sort()

还有另一件事,如果未对变量进行数组排列,则应检查它是否与要删除的项目匹配,如果匹配则将其删除,然后将其删除

if mylist[i] == 2 : 
     del mylist[i]

答案 1 :(得分:2)

根据您的示例尚不清楚,您是否真正想要将扁平化的列表作为输出,还是要保留列表的结构。以及您将拥有多少层嵌套。因此,我编写了一个递归函数,该函数将从深度嵌套的列表中删除项目,而不会对其进行平展和展平。

为使解决方案清晰明了,我将您的输入列表修改为以下内容。

mylist = [[1, 2, 3, 2, 4, 8, 2],2,3,34,2,[[3,4],3,[1,2]]] 

功能

def rem_list_item(l, remval, flatten=False):
    """Recursive function to remove an item from a nested list"""
    flatlist = []
    for item in l:
        if isinstance(item, list):
            # Calling the function itself recursively if the item
            # is a list. 
            if flatten:
                # += will make sure the list is appended without nesting.
                flatlist+=rem_list_item(item, remval, flatten=True)
            else:
                # appended the sublist so that nesting is preserved
                flatlist.append(rem_list_item(item, remval, flatten=False))
        else:
            # If the item is not a list, just append it to the return list
            if item != remval:
                flatlist.append(item)
    return flatlist

不展平

rem_list_item(mylist, 2, flatten=False)
Out: [[1, 3, 4, 8], 3, 34, [[3, 4], 3, [1]]]

具有拉平效果

rem_list_item(mylist, 2, flatten=True)
Out: [1, 3, 4, 8, 3, 34, 3, 4, 3, 1]
相关问题