我在Python中有一个列表的问题。列表索引超出范围。

2024-04-19 03:41:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从一个列表中删除出现在另一个列表中的单词。然后我必须复制第三个列表中没有重复的那些。当我进行比较时,列表索引有问题

语言是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

我想知道为什么会这样。你知道吗


Tags: in版本语言hello列表forlenif
3条回答

使用列表理解:

listThree = [i for i in listOne if i not in listTwo]

可以使用集合来比较列表并删除重复项

>>> listOne = ['Hello','Hello','Every','One','Here']
>>> listTwo = ['Every','Here','Hi','Nice']
>>> listThree = list( set(listOne) - set(listTwo) )
>>> listThree
['Hello', 'One']

您可以使用列表表达式来填充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)

相关问题 更多 >