.remove()方法是从另一个变量中删除单词吗?

时间:2017-10-16 10:59:48

标签: python list duplicates

我有一个字符串列表text

text =  ["this","is","a","string","identifier","identifier","identifier","identifier","identifier","identifier","identifier","identifier","please","help"]

我想摆脱此列表中重复项的部分,而不是全部。因此,例如在上面的列表中有8个单词“identifier”的实例,我想除去其中2个实例,同时将原始实例保留在同一位置;例如,期望的输出将是

text = ["this","is","a","string","identifier","identifier","please","help"]

我有一个我想要删除的重复项的字符串列表,存储在变量delete_words

delete_words = ["identifier"]

要做到这一点,我有:

from collections import Counter
temp_text = text # set up a static temporary variable so indexing issues don't arise
for word in temp_text:
    # keep count of words in _text_
    temp_word_counter_dict = dict(Counter([word for word in text]))
    if word in delete_words and temp_word_counter_dict[word] > 2:
        text.remove(word)

上面代码的问题是

  1. for循环不遍历每个单词,它只迭代前10个单词,因此生成的text变量仍然有4个单词“identifier”而不是2个

  2. 由于某些原因我无法理解,即使我指定temp_text,临时变量text.remove(word)也会删除它的单词,所以我不知道这里发生了什么

  3. 任何人都可以建议我如何从列表中删除重复的单词,同时在原始位置留下2个欺骗?感谢

0 个答案:

没有答案