Removing tuples from a list

后端 未结 4 1596
时光说笑
时光说笑 2021-01-29 04:38

I\'m trying to remove a tuple from a list. If the first element in the list equals \"-NONE-\" I want to remove the whole tuple. I keep getting an error when I try different th

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-29 04:49

    Your immediate error is that list.remove expects an item as its argument, not an index. That is, you'd want to use sent.remove(tuple) rather than sent.remove(sent.index(tuple)). Or alternatively, use del, which does delete by index (del sent[sent.index(tuple)]). However, with either of those fixes you're still going to have issues with your algorithm.

    The reason is that you're iterating over the list at the same time you're removing items from it. Lists iterate by using indexes internally, so when you remove one item, all the later ones move up one space and the next item after the one you've removed will be skipped by the iteration.

    A better approach is usually to use a list comprehension to filter your list:

    def filter(sent):
        return [tuple for tuple in sent if tuple[1] != "-NONE-"]
    

    Note that this returns a new list, rather than modifying the original list in place. If you want to modify things in place, you can do that, but you'll need to iterate over the list in reverse so that the indexes of the values you haven't checked yet won't get changed. Here's one possible way to do that, though they're all a bit ugly:

    def filter(sent):
        for i, val in enumerate(reversed(sent), 1): # iterate in reverse order
            if val[1] == "-NONE-":
                del sent[-i] # del operator removes items by index
    

提交回复
热议问题