Possible Duplicate:
How to check if my list has an item from another list(dictionary)?
这实际上是一个分数的家庭作业。
程序的用户必须写下句子。然后程序检查单词并打印错误的单词(如果错误的单词出现多次,程序必须只打印一次)。错误的单词必须按照它们在句子中出现的顺序打印。
这是我的做法。但有一个问题。由于内置函数已排序,错误单词的出现顺序与句子中出现的顺序不同。还有其他方法可以删除列表中的重复项吗?
字典是从dictionary.txt导入的!!
sentence=input("Sentence:")
dictionary=open("dictionary.txt", encoding="latin2").read().lower().split()
import re
words=re.findall("\w+",sentence.lower())
words=sorted(set(words))
sez=[]
for i in words:
if i not in dictionary:
sez.append(i)
print(sez)
最佳答案
words = filter(lambda index, item: words.index(item) == index, enumerate(words))
它将过滤掉所有重复项并保持顺序。
正如托马斯所指出的,这是一个相当沉重的方法。如果你需要处理更多的单词,你可以使用这个for循环:
dups = set()
filtered_list = []
for word in words:
if not word in dups:
filtered_list.append(word)
dups.add(word)
关于Python 作业 - 比较列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12996811/