我正试图从一个列表中删除出现在另一个列表中的单词。然后,我必须复制第三列表中未重复的内容。比较时,列表索引有问题
语言是python,最新版本。
listOne = ['Hello','Every','One','Here']
listTwo = ['Every','Here','Hi','Nice']
listThree = []
for i in range(len(listOne)):
for j in range(len(listTwo)):
if listOne[i] == listTwo[j]: # <-- error here
listOne.remove(listOne[i])
#Here is the problem
if listOne[i] == listTwo[j]]:
IndexError: list index out of range
我想知道为什么会这样。
答案 0 :(得分:2)
使用列表理解:
listThree = [i for i in listOne if i not in listTwo]
答案 1 :(得分:0)
您可以使用列表表达式来填充list3,并使用for循环和in
语句来满足第一个要求:
listOne = ['Hello','Every','One','Here']
listTwo = ['Every','Here','Hi','Nice']
listThree = [word for word in listOne if not(word in listTwo)]
for word in [word for word in listOne if word in listTwo]:
listOne.remove(word)
答案 2 :(得分:0)
您可以使用集合比较列表并删除重复项
>>> listOne = ['Hello','Hello','Every','One','Here']
>>> listTwo = ['Every','Here','Hi','Nice']
>>> listThree = list( set(listOne) - set(listTwo) )
>>> listThree
['Hello', 'One']