【问题标题】:Compare sentences in Lists A, B, and amend word in B if not matching.比较列表 A、B 中的句子,如果不匹配则修改 B 中的单词。
【发布时间】:2018-10-14 23:50:36
【问题描述】:

python 新手,我有以下问题,我想比较两个列表 A 和 B,它们包含句子。如果 B 中的一个词在 A 中不存在,我想用“foo”替换 B 中的那个词。在新列表或当前列表 B 中。

例子:

ListA = ["I am Sam"]
ListB = ["I am Sam", "Yes me Sam"]

我想得到:

NewList = ["I am Sam", "foo foo Sam"]

提前非常感谢!

【问题讨论】:

  • 您好!到目前为止,您尝试过什么?

标签: python string list set


【解决方案1】:

这是一种使用set 然后是列表理解的方法:

from itertools import chain

ListA = ["I am Sam"]
ListB = ["I am Sam", "Yes me Sam"]

words = set(chain.from_iterable(map(str.split, ListA)))

ListB = [' '.join(i if i in words else 'foo' for i in item.split()) for item in ListB]

['I am Sam', 'foo foo Sam']

【讨论】:

    【解决方案2】:
    from itertools import chain
    ListA = ["I am Sam"]
    ListB = ["I am Sam", "Yes me Sam"]
    words = set(chain.from_iterable(map(str.split, ListA)))
    ListB = [' '.join(i if i in words else 'foo' for i in item.split()) for item in ListB]
    ['I am Sam', 'foo foo Sam']
    

    试试这个:首先使用 set,然后尝试比较它们。

    【讨论】:

      【解决方案3】:
      # two list from the question
      ListA = ["I am Sam"]
      ListB = ["I am Sam", "Yes me Sam"]
      
      # use set() to collect unique words in ListA    
      setA = set([word for i in range(len(ListA)) for word in ListA[i].split(' ')])
      
      # looping ListB and compare each word of each sentence in ListB with ListA
      ListB = [word if word in setA else 'foo' for i in range(len(ListB)) for word in ListB[i].split()]
      
      print(ListB)
      

      这个输出:

      ['I am Sam', 'foo foo Sam']
      

      【讨论】:

      • 谢谢你,肖恩,提醒。注释已添加到代码中。
      • 感谢您和 cmets!很有用!
      猜你喜欢
      • 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
      相关资源
      最近更新 更多