简体   繁体   English

从列表列表中删除特定类的所有元素

[英]Removing all elements of a particular class from a list of lists

I'm in the process of becoming familiar with Python and I'm looking at basic manipulation of "lists" currently. 我正在熟悉Python,我正在研究目前对“列表”的基本操作。

So here's my problem. 所以这是我的问题。

I have a list of lists which contains mostly "string" class elements aside from two integers: Suppose I want to remove only the integer class element so I'm left with an otherwise unaltered list of lists containing only the string elements: 我有一个列表列表,其中除了两个整数之外主要包含“字符串”类元素:假设我只想删除整数类元素,所以我留下了一个仅包含字符串元素的未更改的列表列表:

ie My original list is the following: 即我原来的清单如下:

    listoflists=[['Juice', 'Pizza', 'Potatoes', 'Bananas', 5, 10],
 ['eggs', 'ham', 'chicken', 'Pineapple'],
 'Onions']

and I want this to become the following: 我希望这成为以下内容:

listoflist=[['Juice', 'Pizza', 'Potatoes', 'Bananas'],
 ['eggs', 'ham', 'chicken', 'Pineapple'],
 'Onions']

Thus far I've found out how to remove integer class element from a singular list with the following: 到目前为止,我已经找到了如何从单个列表中删除整数类元素,具体如下:

 no_integer_list = [x for x in listA if not isinstance(x, int)]

But I'm struggling to get my head around how to apply this to a list of lists. 但是我很难理解如何将其应用到列表列表中。

I was thinking of making a for loop to read each list within the multilist and apply the above code to each, but I'm not sure how to do this. 我正在考虑制作一个for循环来读取多列表中的每个列表并将上面的代码应用到每个列表,但我不知道如何做到这一点。

Any help with this will be much appreciated. 任何帮助都将非常感激。 Many thanks in advance. 提前谢谢了。

Assuming that you only have one level of sublists (and your last element is a list and not a string), you could use a nested list comprehension like so 假设您只有一个级别的子列表(并且您的最后一个元素是列表而不是字符串),您可以使用嵌套列表解析

filtered = [[x for x in sublist if not isinstance(x, int)] for sublist in listoflists]

Outputs : 产出

[['Juice', 'Pizza', 'Potatoes', 'Bananas'], ['eggs', 'ham', 'chicken', 'Pineapple'], ['Onions']]

If your last element is intentionally a string (or could possibly be an int ), I would scrap the messy one liners and just write a simple function like so 如果你的最后一个元素是故意的一个字符串(或者可能是一个int ),我会废掉凌乱的一个衬里,然后写一个简单的函数就像这样

def filter_list(listoflists):
    newlist = []
    for element in listoflists:
        if isinstance(element, list):
            newlist.append([x for x in element if not isinstance(x, int)])
        elif isinstance(element, int):
            continue
        else:
            newlist.append(element)
    return newlist

Note that this is designed to simply remove all int types- other types will remain. 请注意,这旨在简单地删除所有int类型 - 其他类型将保留。 If you want to only retain strings and discard all other types, you could use stop using the negation and have 如果你只想保留字符串并丢弃所有其他类型,你可以使用停止使用否定并拥有

def filter_list(listoflists):
    newlist = []
    for element in listoflists:
        if isinstance(element, list):
            newlist.append([x for x in element if isinstance(x, str)])
        elif isinstance(element, str):
            newlist.append(element)
    return newlist 
>>> [[i for i in item if not isinstance(i, int)] if isinstance(item, list) else item for item in listoflists]
[['Juice', 'Pizza', 'Potatoes', 'Bananas'],
 ['eggs', 'ham', 'chicken', 'Pineapple'],
 'Onions']

UPDATE: just for completeness if you outer list also has integers and you want to remove those too: 更新:只是为了完整性,如果你的外部列表也有整数,你也想删除它们:

[[i for i in item if not isinstance(i, int)] if isinstance(item, list) else item 
 for item in listoflists if not isinstance(item, int)]

You approach is completly fine, but you need to do it for every sublist by using the map() function or a list comprehension. 您接近完全正常,但您需要使用map()函数或列表推导为每个子列表执行此操作。

>>> l = [['Juice', 'Pizza', 'Potatoes', 'Bananas', 5, 10], ['eggs', 'ham', 'chicken', 'Pineapple'], 'Onions']
>>> map(lambda x: filter(lambda y: not isinstance(y,int),x),l)
[['Juice', 'Pizza', 'Potatoes', 'Bananas'], ['eggs', 'ham', 'chicken', 'Pineapple'], 'Onions']

Instead of using filter() and map(), you can also use the equivalent list comprehension method. 您也可以使用等效列表推导方法,而不是使用filter()和map()。

A flexible recursive solution for any number of nested levels (even varying depths) and for both lists and tuples (output will be list though): 一个灵活的递归解决方案,适用于任意数量的嵌套级别(甚至是不同深度)以及列表和元组(输出将列出):

eliminate_int = lambda l: [eliminate_int(x) if isinstance(x, list) or isinstance(x, tuple) \
                           else x for x in l if not isinstance(x, int)]

listoflists=[ ['Juice', 'Pizza', 'Potatoes', 'Bananas', 5, 10],
              ['eggs', 'ham', 'chicken', 'Pineapple'],
              'Onions' ]

print(eliminate_int(listoflists))

Output: 输出:

[['Juice', 'Pizza', 'Potatoes', 'Bananas'], ['eggs', 'ham', 'chicken', 'Pineapple'], 'Onions']

See this code running on ideone.com 请参阅ideone.com上运行的此代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM