python - 检查项目是否在列表中的最快方法 - Python

标签 python python-2.7 list python-3.x

<分区>

我在用 Python 制作词汇表时遇到了问题。我的代码遍历了一个大约 2.3MB 的文档中的每个单词,并检查该单词是否在字典中,如果不在,它会附加到列表中

问题是,它花了很长时间(我什至还没有完成)。我该如何解决这个问题?

代码:

words = [("_", "hello"), ("hello", "world"), ("world", "."), (".", "_")] # List of a ton of tuples of words
vocab = []
for w in words:
    if not w in vocab:
        vocab.append(w)

最佳答案

除非你需要 vocab 有一个特定的顺序,你可以这样做:

vocab = set(words)

关于python - 检查项目是否在列表中的最快方法 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41337529/

相关文章:

python - max 如何用于混合类型列表

python - 使用Bio.SeqIO编写单行FASTA

r - 如何使用 R 选择/查找距离列表 (X/Y) 一定距离内的坐标

Python:如何解决TypeError:循环中需要一个整数

python - 在 Python 的值列表上压缩和应用函数列表

python-2.7 - 根据列名堆叠在 Pandas 数据框中

python - 在 Python 中使用花括号初始化 Set

python - 如何在 Python 2.7 中使用函数注解

python - SQLAlchemy - 创建无符号 BigInteger 的正确方法

python - 如何在 Pandas 中选择 'last business day of the month'?