0

嗨,我有一个元组列表

a = [[('bring', 'VBG'), ('puffy', 'NN'), ('eyes', 'NNS'), ('back', 'RB')], [('droopy','NN'), ('eyes', 'NNS')]]

现在我想删除多余的元组,意味着输出应该像

a = [[('bring', 'VBG'), ('puffy', 'NN'), ('eyes', 'NNS'), ('back', 'RB')], [('droopy', 'NN')]]

tuple ('eye', 'NNS')已被删除

4

1 回答 1

2

使用sets

单线:

>>> seen = set()
>>> [ [y for y in x if y not in seen and not seen.add(y)] for x in a]
[[('bring', 'VBG'), ('puffy', 'NN'), ('eyes', 'NNS'), ('back', 'RB')], [('droopy', 'NN')]]

上面的代码等价于:

>>> a = [[('bring', 'VBG'), ('puffy', 'NN'), ('eyes', 'NNS'), ('back', 'RB')], [('droopy','NN'), ('eyes', 'NNS')]]
>>> seen = set()
>>> out_lis = []
for x in a:
    temp = []
    for y in x:
        if y not in seen:
            seen.add(y)
            temp.append(y)
    out_lis.append(temp)
...     
>>> out_lis
[[('bring', 'VBG'), ('puffy', 'NN'), ('eyes', 'NNS'), ('back', 'RB')], [('droopy', 'NN')]]
于 2013-06-27T18:05:48.613 回答