【问题标题】:Delete list word combination python 3删除列表词组合python 3
【发布时间】:2018-07-17 00:11:07
【问题描述】:

我有一个字符串列表,我想搜索一个单词组合。 如果组合不存在,则删除列表。有没有python列表 理解会起作用吗?

word_list = ["Dogs love ice cream", "Cats love balls", "Ice cream", "ice cream is good with pizza", "cats hate ice cream"]

keep_words = ["Dogs", "Cats"] 

Delete_word = ["ice cream"]

删除其中包含冰淇淋的单词,但如果句子中包含狗或猫,则保留它。

Desired_output = ["Dogs love ice cream", "Cats love balls", "cats hate ice cream"] 

在尝试此代码时也尝试了 AND 和 OR,但无法正确组合。

output_list = [x for x in  word_list if "ice cream" not in x]

【问题讨论】:

  • ice cream 需要在一起吗?就像这句话会被认为是有效的:keep cream over the ice?
  • 我在想它在一起“冰淇淋”但很好的一点
  • 最后一个是包含cat 而不是cats!
  • 我将编辑的好地方 Kasramvd 猫

标签: python arrays list for-loop


【解决方案1】:

这是一个列表理解解决方案:

[x for x in word_list if any(kw.lower() in x.lower() for kw in keep_words) 
 or all(dw.lower() not in x.lower() for dw in Delete_word)]
# ['Dogs love ice cream', 'Cats love balls', 'cats hate ice cream']

这也为删除单词列表中的多个单词增加了灵活性。

说明

如果以下任一为True,则遍历列表并保留单词:

  • 任何保留字都在 x 中
  • x中没有删除的词

我从您的示例中推测您希望它不区分大小写,因此请对单词的小写版本进行所有比较。

两个有用的函数是any()all()

【讨论】:

  • Pault 非常有趣,我没有想到“任何和所有” --- 非常感谢您的帮助
【解决方案2】:

作为一种优化方法,您可以将 keep_worddelete_words 放在集合中,并使用 itertools.filterfalse() 过滤掉列表:

In [48]: def key(x):
             words = x.lower().split()
             return keep_words.isdisjoint(words) or not delete_words.isdisjoint(words)
   ....: 

In [49]: keep_words = {"dogs", "cats"}

In [51]: delete_words = {"ice cream"}

In [52]: list(filterfalse(key ,word_list))
Out[52]: ['Dogs love ice cream', 'Cats love balls', 'cats hate ice cream']

【讨论】:

  • Kasramvd 一个非常非常非常有趣的技术我喜欢它 - 谢谢你的帮助
  • return keep_words.isdisjoint(words) or Delete_word.intersection(words) 可以改进 not 以生成这样的交集:return keep_words.isdisjoint(words) or not Delete_word.is_disjoint(words)
  • @Jean-FrançoisFabre 那就更好了!
  • 也可以将x.lower() 替换为x.casefold(),因此德语“beta”被降低为双“s”。比单个 str.lower 更强大
【解决方案3】:
>>> list(filter(lambda x: not any(i in x for i in Delete_word)
...                       or  any(i in x for i in keep_words), word_list))
['Dogs love ice cream', 'Cats love balls', 'Ice cream']

为不区分大小写的实现相应地修改它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多