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"]
非常感谢!
答案 0 :(得分:2)
这是使用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']
答案 1 :(得分:1)
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 ,然后尝试进行比较。
答案 2 :(得分:1)
# 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']