Removing tuples from a list

后端 未结 4 1657
时光说笑
时光说笑 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:46

    Instead of defining your own filter function, use the built-in function:

    z = [('uh', 'UH'), ('i', 'PRP'), ('think', 'VBP'), (',', ','), ('*0*', '-NONE-'), ('it', 'PRP'), ("'s", 'BES'), ('because', 'IN'), ('i', 'PRP'), ('get', 'VBP'), ('*', '-NONE-'), ('to', 'TO'), ('be', 'VB'), ('something', 'NN'), ('that', 'WDT'), ('i', 'PRP'), ("'m", 'VBP'), ('not', 'RB'), ('*T*', '-NONE-'), ('.', '.')]
    z_filtered = filter(lambda item: item[1] != '-NONE-', z)
    

    Or use itertools.ifilter():

    import itertools as it
    filtered = list(it.ifilter(lambda item: item[1] != '-NONE-', z))
    

    Those are both a bit slower than @Blckknght's or @user2357112's list comprehension. This is competitive though:

    def f(z):
        for item in z:
            if item[1] != '-NONE-':
                yield item
    filtered = list(f(z))
    

提交回复
热议问题