从列表列表中删除字符串

时间:2019-03-08 18:30:51

标签: python

我正在尝试从列表列表中删除字符串,同时保留内部列表。

示例:

输入

x = [["banana", "dog", "potato"], ["dog", "potato"], ["banana"], ["dog", "potato"]]

我使用一个函数

x.remove_from_internal_lists("banana") # Invented function

我想要的输出

x = [["dog", "potato"], ["dog", "potato"], ["dog", "potato"]]

我在一个列表中了解.remove()和其他方法,但是我不确定如何使用它们删除字符串并保留内部列表。

4 个答案:

答案 0 :(得分:2)

您可以使用列表理解:

lst = [["banana", "dog", "potato"], ["dog", "potato"], ["banana"], ["dog", "potato"]]

lst = [[y for y in x if y != 'banana'] for x in lst if x != ['banana']]
# [['dog', 'potato'], ['dog', 'potato'], ['dog', 'potato']]

答案 1 :(得分:2)

您需要遍历x中的每个列表,并检查该值是否在子列表中。如果是的话,将其删除。如果没有,请继续。

def remove_from_internal_lists(l, value):
    for y in l:
        if value in y:
            y.remove(value)
    return [x for x in l if x]  # removes any empty lists

并称呼它

>>> new_x = remove_from_internal_lists(x, "banana")
>>> new_x
[['dog', 'potato'], ['dog', 'potato'], ['dog', 'potato']]

答案 2 :(得分:2)

其他答案涵盖了如何复制此行为,但是将函数添加到类型的方法是子类化:

class NestedList(list):
    def remove_from_internal_lists(self, word):
        forward_final_index = len(self) - 1
        for reversed_index, sub_list in enumerate(reversed(self)):
            if isinstance(sub_list, list) and word in sub_list:
                if len(sub_list) == 1:
                    # Modifying a list under iteration is normally a Bad Idea(tm):
                    # This is possible because we are iterating in reverse which
                    # guarantees all invalidated indices have already been processed
                    # and allows for multiple copies of [word] in our outer list.
                    # Additionally, we preserve any empty lists already present
                    del self[forward_final_index - reversed_index]
                else:
                    sub_list.remove(word)

注意:大型注释是必需的:您所做的事情通常是一个坏主意 tm ,应向您做出解释,以便将来的维护者(包括您自己) )不会被误导。

这使我们能够使用您的“发明的功能”,NestedLists的作用类似于列表加号:

>>> lst = [["banana", "dog", "potato"], ["dog", "potato"], ["banana"], ["dog", "potato"]]
>>> nlst = NestedList(lst)
>>> nlst.remove_from_internal_lists("banana")
>>> nlst
[['dog', 'potato'], ['dog', 'potato'], ['dog', 'potato']]

答案 3 :(得分:1)

这是一个使用递归的解决方案,该解决方案可与列表中的任何嵌套深度配合使用,并且在重复的情况下还删除所有出现的指定项目。也可用于由内部列表和非列表组成的“混合”列表:

def remove_from_inner_lists(the_list, the_item):
    for e in reversed(the_list):
        if (type(e)) == list:
            remove_from_inner_lists(e, the_item)
        elif e == the_item:
            the_list.remove(e)

输出:

x = [[["banana", "dog", "potato"], ["dog", "potato"], "banana"], ["banana"], ["dog", "potato"]]

remove_from_inner_lists(x, "banana")

print (x)

[[['dog', 'potato'], ['dog', 'potato']], [], ['dog', 'potato']]