您好我有一个元组列表
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')
已被删除
答案 0 :(得分: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')]]