【问题标题】:Delete item from a list of tuples从元组列表中删除项目
【发布时间】:2016-04-03 10:40:37
【问题描述】:
L = [('The', 'DT'), ('study', 'NN'), ('guide', 'NN'), ('does', 'VBZ'), ('not', 'VBZ'), ('discuss', 'VBZ'), ('much', 'NN'), ('of', 'IN'), ('the', 'DT'), ('basics', 'NN'), ('of', 'IN'), ('ethics.', 'NN')]

我想删除具有除 'NN' 和 'DT' 之外的标签的元组 我尝试了pop方法它不起作用。尝试解压缩这两个元组,但元组是不可变的。那么如何删除它们。

【问题讨论】:

  • 也许你可以使用namedtuples?元素像字典键一样被索引。

标签: python-2.7 python-3.x nlp


【解决方案1】:

您必须弹出或删除他们的索引才能使其工作,例如,您可以使用L.pop(L.index(('The', 'DT'))) 而不是L.pop(('The', 'DT'))

没有测试过,但如果我对你想要的东西没有错误的想法,这应该可以工作。

这种方式会构建一个您要删除的索引列表,然后将其删除(否则,您将在查看列表时更改列表的大小,这对您不利)。

invalid_tuples = []
for i, t in L:
    if t[1] not in ('NN', 'DT'):
        invalid_tuples.append(i)
for i in invalid_tuples:
    del L[i]

或者作为一种单一的解决方案:

[i for i in L if i[1] in ('NN', 'DT')]

【讨论】:

    【解决方案2】:
    >>> L = [('The', 'DT'), ('study', 'NN'), ('guide', 'NN'), ('does', 'VBZ'), ('not', 'VBZ'), ('discuss', 'VBZ'), ('much', 'NN'), ('of', 'IN'), ('the', 'DT'), ('basics', 'NN'), ('of', 'IN'), ('ethics.', 'NN')]
    >>> [(word, tag) for word, tag in L if tag not in ['DT', 'NN']]
    [('does', 'VBZ'), ('not', 'VBZ'), ('discuss', 'VBZ'), ('of', 'IN'), ('of', 'IN')]
    >>> [(word, tag) for word, tag in L if tag in ['DT', 'NN']]
    [('The', 'DT'), ('study', 'NN'), ('guide', 'NN'), ('much', 'NN'), ('the', 'DT'), ('basics', 'NN'), ('ethics.', 'NN')]
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-01
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多